The reduce()
method reduces the array to a single value.
The reduce()
method executes a provided function for each value of the array (from left-to-right).
The return value of the function is stored in an accumulator (result/total).
Note: reduce()
does not execute the function for array elements without values.
Note: this method does not change the original array.
// Subtract the numbers in the array, starting from the beginning:
var numbers = [175, 50, 25];
function myFunc(total, num) {
return total - num;
}
console.log(numbers.reduce(myFunc));
console.log(numbers); // Reduce does not change the array
// Round all the numbers in an array, and display the sum:
var numbers = [15.5, 2.3, 1.1, 4.7];
function getSum(total, num) {
return total + Math.round(num);
}
console.log(numbers.reduce(getSum));