I am trying to group the people by their age and as you can see, my code works with the reduce method. I managed to get this working but now I want to do the same with forEach method. Here’s my code:
{name:'Kyle', age:42},
{name:'Suk', age:34},
{name:'Lol', age:35},
{name:'Pol', age:23},
{name:'Kol', age:23}
]
people.reduce((groupedPeople, person)=>{
const age = person.age
if(groupedPeople[age] == null) {groupedPeople[age]=[]
}
groupedPeople[age].push(person)
return groupedPeople
})
Advertisement
Answer
Reduce accepts initial value that you update each iteration and return. So if you wish to use forEach, just move initial value before the forEach:
const people = [{
name: 'Kyle',
age: 42
},
{
name: 'Suk',
age: 34
},
{
name: 'Lol',
age: 35
},
{
name: 'Pol',
age: 23
},
{
name: 'Kol',
age: 23
}
]
const groupedPeople = {}
people.forEach((person) => {
const age = person.age
if (groupedPeople[age] == null) {
groupedPeople[age] = []
}
groupedPeople[age].push(person)
})
console.log(groupedPeople)However, I am not sure why you wish to do that. Code with reduce is much cleaner.