I still don't understand what .reduce() does

the exercise I’m doing is: https://www.codecademy.com/courses/introduction-to-javascript/lessons/javascript-iterators/exercises/reduce

I read through all of it and did what it told me to do. I still don’t get it. Can someone explain it to me in another way? thanks :smile:

The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step until there are no more elements to add…

2 Likes

Hi there and welcome to the forums!

Essentially what this array method is there for is to simplify the combination of array elements. So lets think about the example array [1, 2, 3, 4, 5]. If we wanted to get the sum of all elements of this array we could do this in a few ways.

let array = [1, 2, 3, 4, 5];
let total = 0;

total += array[0];
total += array[1];
total += array[2];
total += array[3];
total += array[4];

This would be the most basic way of doing it. Now of course this can be done more efficiently using a for loop like so.
2.

let array = [1, 2, 3, 4, 5];
let total = 0;

for (let i = 0; i < array.length; i++) {
    total += array[i];
}

This simplifies part 1 a bit but is still a bit excessive. However you can see the general idea. We have a total variable that we add each element to, eventually ending up with the final result of the sum of all variables.

  1. The reduce method
let array = [1, 2, 3, 4, 5]

let total = array.reduce((total, arrayValue) => total + arrayValue);

We can see immediately that this is a lot more compact than the last two methods, fitting into only 2 lines (and even a single line if you don’t assign the array first like so.

[1, 2, 3, 4, 5].reduce((total, arrayValue) => total + arrayValue);

All of the above code blocks are doing exactly the same thing, it’s just the reduce method is a lot cleaner in the way it is written. All it’s doing is collapsing the array into a single value based on the function provided same as any of the above code blocks were doing.

2 Likes