Skip to content
Advertisement

How to write this function with forEach?

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

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

However, I am not sure why you wish to do that. Code with reduce is much cleaner.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement