Skip to content

Instantly share code, notes, and snippets.

@snsxn
Created August 26, 2022 14:42
Show Gist options
  • Save snsxn/b7f31f704249617fb67252c4338dd667 to your computer and use it in GitHub Desktop.
Save snsxn/b7f31f704249617fb67252c4338dd667 to your computer and use it in GitHub Desktop.
One-line group an Array by an Object Property - JavaScript ES2015, ES6
const groupBy = (arr, groupFn) => arr.reduce((grouped, obj) => ({...grouped,[groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj], }), {});
// Using it
const people = [
{ name: 'Matt' },
{ name: 'Sam' },
{ name: 'John' },
{ name: 'Mac' },
];
groupBy(people, (person) => person.name.length);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment