Created
July 1, 2020 07:48
-
-
Save robinjl/34a16b2a207d10a1938eaca24128610c to your computer and use it in GitHub Desktop.
group_by_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
// source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce | |
let people = [ | |
{ name: 'Alice', age: 21 }, | |
{ name: 'Max', age: 20 }, | |
{ name: 'Jane', age: 20 } | |
]; | |
function groupBy(objectArray, property) { | |
return objectArray.reduce(function (acc, obj) { | |
let key = obj[property] | |
if (!acc[key]) { | |
acc[key] = [] | |
} | |
acc[key].push(obj) | |
return acc | |
}, {}) | |
} | |
let groupedPeople = groupBy(people, 'age') | |
// groupedPeople is: | |
// { | |
// 20: [ | |
// { name: 'Max', age: 20 }, | |
// { name: 'Jane', age: 20 } | |
// ], | |
// 21: [{ name: 'Alice', age: 21 }] | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment