Книга: Functional Programming in JavaScript
Назад: Array.prototype.filter()
Дальше: Honorable mentions

Array.prototype.reduce()

Sometimes called fold, the 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.

Note

Syntax:

Parameters:

  • : This function combines two objects into one, which is returned. With these parameters:
    • : This parameter gives the value previously returned from the last invocation of the callback, or the , if supplied
    • : This parameter gives the current element being processed in the array
    • : This parameter gives the index of the current element in the array
    • : This parameter gives the array being processed
  • : This function is optional. Object to use as the first argument to the first call of the .

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 );
Назад: Array.prototype.filter()
Дальше: Honorable mentions

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)