Created
October 17, 2023 15:43
-
-
Save kevboutin/a7a99fcfaa587179257e01538cdf3d7e to your computer and use it in GitHub Desktop.
Group an array by object property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const groupBy = (arr, groupFn) => { | |
const grouped = {}; | |
for (const obj of arr) { | |
const groupName = groupFn(obj); | |
if (!grouped[groupName]) { | |
grouped[groupName] = []; | |
} | |
grouped[groupName].push(obj); | |
} | |
return grouped; | |
}; | |
const people = [ | |
{ name: 'Matt' }, | |
{ name: 'Sam' }, | |
{ name: 'Jeff' }, | |
{ name: 'Mac' }, | |
]; | |
const groupedByNameLength = groupBy(people, (person) => person.name.length); | |
/** | |
{ | |
'3': [ { name: 'Sam' }, { name: 'Mac' } ], | |
'4': [ { name: 'Matt' }, { name: 'Jeff' } ] | |
} | |
*/ | |
console.log(groupedByNameLength); | |
// Better version: | |
const groupByBest = (arr, groupFn) => | |
arr.reduce( | |
(grouped, obj) => ({ | |
...grouped, | |
[groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj], | |
}), | |
{} | |
); | |
const people = [ | |
{ name: 'Matt' }, | |
{ name: 'Sam' }, | |
{ name: 'Jeff' }, | |
{ name: 'Mac' }, | |
]; | |
const groupedByNameLength = groupByBest(people, (person) => person.name.length); | |
/** | |
{ | |
'3': [ { name: 'Sam' }, { name: 'Mac' } ], | |
'4': [ { name: 'Matt' }, { name: 'Jeff' } ] | |
} | |
*/ | |
console.log(groupedByNameLength); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment