groupby javascript by instances

Solutions on MaxInterview for groupby javascript by instances by the best coders in the world

showing results for - "groupby javascript by instances"
Felipe
08 Mar 2018
1let people = [
2  { name: 'Alice', age: 21 },
3  { name: 'Max', age: 20 },
4  { name: 'Jane', age: 20 }
5];
6
7function groupBy(objectArray, property) {
8  return objectArray.reduce(function (acc, obj) {
9    let key = obj[property]
10    if (!acc[key]) {
11      acc[key] = []
12    }
13    acc[key].push(obj)
14    return acc
15  }, {})
16}
17
18let groupedPeople = groupBy(people, 'age')
19// groupedPeople is:
20// {
21//   20: [
22//     { name: 'Max', age: 20 },
23//     { name: 'Jane', age: 20 }
24//   ],
25//   21: [{ name: 'Alice', age: 21 }]
26// }
27