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:
JavaScript
x
16
16
1
{name:'Kyle', age:42},
2
{name:'Suk', age:34},
3
{name:'Lol', age:35},
4
{name:'Pol', age:23},
5
{name:'Kol', age:23}
6
]
7
8
9
people.reduce((groupedPeople, person)=>{
10
const age = person.age
11
if(groupedPeople[age] == null) {groupedPeople[age]=[]
12
}
13
groupedPeople[age].push(person)
14
return groupedPeople
15
})
16
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:
JavaScript
1
33
33
1
const people = [{
2
name: 'Kyle',
3
age: 42
4
},
5
{
6
name: 'Suk',
7
age: 34
8
},
9
{
10
name: 'Lol',
11
age: 35
12
},
13
{
14
name: 'Pol',
15
age: 23
16
},
17
{
18
name: 'Kol',
19
age: 23
20
}
21
]
22
23
24
const groupedPeople = {}
25
people.forEach((person) => {
26
const age = person.age
27
if (groupedPeople[age] == null) {
28
groupedPeople[age] = []
29
}
30
groupedPeople[age].push(person)
31
})
32
33
console.log(groupedPeople)
However, I am not sure why you wish to do that. Code with reduce is much cleaner.