The reduce() method will reduce the array to a single value.
The reduce() method will reduce the array to a single value.
The reduce() method executes a function for each value of the array from start to end.
The return value of the function is stored in an accumulator variable.
The reduce() does not run the function for array elements without values.
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameter | Require | Description |
---|---|---|
function(total,currentValue, currentIndex,arr) | Required. | A function to be run for each element in the array. |
initialValue | Optional. | A value to be passed to the function as the initial value |
function(total,currentValue, currentIndex,arr)
Argument | Require | Description |
---|---|---|
total | Required. | The initialValue, or the previously returned value of the function |
currentValue | Required. | The value of the current element |
currentIndex | Optional. | The array index of the current element |
arr | Optional. | The array object the current element belongs to |
Returns the accumulated result from the last call of the callback function
Get the sum of the numbers in the array:
var numbers = [65, 44, 12, 4]; function getSum(total, num) { return total + num; } console.log( numbers.reduce(getSum) );//from w ww. j ava 2 s. c om //Round all the numbers in an array, and display the sum: var numbers = [15.5, 2.3, 1.1, 4.7]; function getSum1(total, num) { return total + Math.round(num); } console.log( numbers.reduce(getSum1, 0));