I’ll show you 3 examples of how you can use the reduce method and explain what's going on in the code. For the examples ill be creating a variable called people that is an array with 9 objects(person) inside, and another variable for result.
Count the number of people in the array and return the number.
The first thing I do is set the result to a new value of “people.reduce()”. Then inside of the reduce method I have a callback function that takes in an accumulator(acc) and the people array. Then return acc + 1 with an initial value of 0. So what's going on is the accumulator will start at index and add 1 to every person in the array. If you decide to try it out on your own, you should receive 9 people as the result.
Sum up all the ages of every single person inside of the array.
In this example it's almost the same as example 1 but, this time we are looking for the sum of all the people's ages. Inside of the reduce function we do the same as the last example with a callback function that takes in the accumulator and people array. Then we return the accumulator and add the people.age starting at an initial value of 0. The accumulator will loop through the array and grab each person's age and add them together.
Return the people array with the names of every person.
For this example, we use the same reduce method but we return an array with the spread operator of the accumulator(array) and the person.name. Then setting the initial value to an empty array. If you run the code you should end up with an array of all the people’s names.
This is the best that I can explain using the reduce method. I think that in some situations it would be more beneficial to use a different method but it's always nice to be able to use the reduce method on the fly.