reduce method
The reduce
method reduces
an array to a single value. For example,
using this method, you can easily find
the sum of the array elements (that is,
the array will be reduced to one value
- to the sum of the elements).
As the first parameter, the reduce
method receives a function that will be
sequentially executed for each element
of the array, starting from the first. You
can pass 4
parameters to this function. If
these parameters are present (they are not
required), then the first one will
automatically get intermediate result,
the second one will get the array element,
the third one - its number in the array
(index), and the fourth one - the array
itself.
The intermediate result is a variable that
will accumulate the value that the reduce
method will return when it iterates through
all the elements of the array. For example,
you can sequentially accumulate the sum
of array elements there: first, put the
first element, on the next iteration of
the loop already the sum of the first
element and the second, on the next iteration
- the sum of the first, second and third. And
so on until the array ends. The function that
reduce
takes must return the new
value of the intermediate result.
The second parameter of the reduce
method is the initial value of the intermediate
result. If it is not specified, then it will
be equal to the first element of the array,
and element processing will start from
the second element.
Syntax
array.reduce(function(intermediate result, element, index, array) {
return new intermediate result;
}, initial value);
Example
We find the sum of array elements:
let arr = [1, 2, 3, 4, 5, 6];
let res = arr.reduce(function(sum, elem) {
return sum + elem;
}, 0);
console.log(res);
The code execution result:
21
Example
Let's find the sum of all positive numbers in an array:
let arr = [1, -2, -3, 4, 5, -6];
let res = arr.reduce(function(sum, elem) {
if (elem >= 0) {
return sum + elem;
} else {
return sum;
}
}, 0);
console.log(res);
The code execution result:
10