Sometimes called fold, the reduce()
function is used to accumulate all the values of the array into one. The callback needs to return the logic to be performed to combine the objects. In the case of numbers, they're usually added together to get a sum or multiplied together to get a product. In the case of strings, the strings are often appended together.
Syntax: arr.reduce(callback [, initialValue]);
Parameters:
callback()
: This function combines two objects into one, which is returned. With these parameters:previousValue
: This parameter gives the value previously returned from the last invocation of the callback, or the initialValue
, if suppliedcurrentValue
: This parameter gives the current element being processed in the arrayindex
: This parameter gives the index of the current element in the arrayarray
: This parameter gives the array being processedinitialValue()
: This function is optional. Object to use as the first argument to the first call of the callback
.Examples:
var numbers = [1,2,3,4]; // sum up all the values of an array console.log([1,2,3,4,5].reduce(function(x,y){return x+y}, 0)); // sum up all the values of an array console.log([1,2,3,4,5].reduce(function(x,y){return x+y}, 0)); // find the largest number console.log(numbers.reduce(function(a,b){ return Math.max(a,b)}) // max takes two arguments );