Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: document the function arguments for the reduce operator

...

The reduce() operator applies a function, given as its first argument, to members of an array in left associative order. The function should take two arguments.  An optional second argument to the operator is the default value for the reduction.

...

If the default value is supplied, reduce() returns the result of applying function to the default value and the first item in the array, then applying the function to that result and the 2nd item, etc. If array contains no items, reduce() returns the default value.

The function (supplied to the reduce() operator as its first argument) should take at least two arguments. The first argument accumulates the result, starting with the second operator argument, if any, as described above. The function's second argument is each element, in turn, of the array upon which reduce is operating. There is also a third argument, which is the current index in the array, and a fourth argument, which is the entire array.

Code Block
languagejavascript
themeConfluence
c = [4, 5, 6];
c.reduce(function(a,b){a + b})     // returns 15
c.reduce(function(a,b){a + b}, 10) // returns 25
c.reduce(function(a,b){a - b})     // returns -7; note left associativity


d = [];
d.reduce(function(a,b){a + b})     // returns 0
d.reduce(function(a,b){a + b}, 15) // returns 15 


m = [76];
m.reduce(function(a,b){a + b})     // returns 76
m.reduce(function(a,b){a + b}, 15) // returns 91

...