How To Group Objects In Array By Unique Properties In Javascript?
So My problem is that I am trying to group my array of contacts by "County", My only problem is that my grouping function works... not really. If you run my code, you'll see that it groups as expected; My only issue is that Washington, Florida and Washington, Alabama are two different counties that shouldn't be grouped together. I know I can try to append an additional piece of info to the county in order to make it unique, like so: Washington,FL & Washington,AL. That will probably solve the problem but will require me to mutate my dataset or write another lookup function for State codes.
So is there a way that I can simply make sure that my function groups by unique county based on each data it has in hand on each object (like the State)?
Thanks for your help.
function groupBy(array, key) {
return array.reduce((r, a) => {
;(r[a[String(key)]] = r[a[String(key)]] || []).push(a)
return r
}, {})
}
const contacts = [
{
County: 'Washington',
State: 'Florida',
Country: 'United States',
Name: 'Bob Michael',
},
{
County: 'Washington',
State: 'Alabama',
Country: 'United States',
Name: 'John Doe',
},
]
console.log(groupBy(contacts, "County"))
Answer
You could take a group of keys and join the values to a single key.
function groupBy(array, keys) {
return array.reduce((r, o) => {
const key = keys.map(k => o[k]).join('|');
(r[key] = r[key] || []).push(o);
return r;
}, {});
}
const contacts = [
{
County: 'Washington',
State: 'Florida',
Country: 'United States',
Name: 'Bob Michael',
},
{
County: 'Washington',
State: 'Alabama',
Country: 'United States',
Name: 'John Doe',
},
]
console.log(groupBy(contacts, ["Country", "State", "County"]))
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM