Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Created October 17, 2023 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevboutin/a7a99fcfaa587179257e01538cdf3d7e to your computer and use it in GitHub Desktop.
Save kevboutin/a7a99fcfaa587179257e01538cdf3d7e to your computer and use it in GitHub Desktop.
Group an array by object property
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