Saturday, March 24, 2018

Reduce

Reduce takes all of the elements in an array, and reduces them into a single value.

reduce passes your callback four arguments:

The current value
The previous value
The current index
The array you called reduce on

internal of reduce

var numbers = [1, 2, 3, 4, 5],
    total = 0;
   
numbers.forEach(function (number) {
    total += number;
});

While this isn't a bad use case for forEach, reduce still has the advantage of allowing us to avoid mutation. With reduce, we would write:


var total = [1, 2, 3, 4, 5].reduce(function (previous, current) {
    return previous + current;
}, 0);

No comments:

Followers

Link