4 ms·
Hardly shorter than just writing the for loop, i.e. the example in python groupByAge = collections.defaultdict(list) for person in people: gro
by badjeans 5y ago
Hardly shorter than just writing the for loop, i.e. the example in python
groupByAge = collections.defaultdict(list)
for person in people:
groupByAge[person["age"]].append(person)
- shhsshs 5y agoIn JS you would also need to check if the key exists first (so you can add it). I think the minimal example would be: const groupByAge = {} for (const person in people) { if (!groupByAge[person.age]) { groupByAge[person.age] = [] } groupByAge[person.age].push(person) } IMO it is a very nice change to now be able to write: const groupByAge = people.groupBy(p => p.age)
- SahAssar 5y agoA reduce version seems quite okay to me though, and keeps it pretty functional-styled. const groupByAge = people.reduce((previous, current) => { if (!previous[current.age]) previous[current.age] = [] previous[current.age].push(current) return previous }, {})