Design & Download
Your JS Library
in Seconds!!!

Snippet: reduce()

Written by Christopher West (cwest) on November 29, 2015.
The reduce() method applies a function against an accumulator and each value of the array or object to reduce it to a single value.
function reduce(arrOrObj, accumulator, opt_initial) {
  var hasInitial = arguments.length > 2;
  walk(arrOrObj, function(value, key) {
    opt_initial = hasInitial
      ? accumulator(opt_initial, value, key, arrOrObj)
      : (hasInitial = 1, value);
  });
  if (hasInitial) {
    return opt_initial;
  }
  throw new TypeError('Reduce of empty subject with no initial value');
}

reduce(...) API Documentation

Description

Applies a function against an accumulator and each value of the array, array-like object or object has to reduce it to a single value.

Parameters

  1. arrOrObj {Array|Object}:
    The array (or array-like object) or object whose values will be traversed with an accumulator function.
  2. accumulator {Function}:
    Function to execute on each value. The return value of this function will be passed into this same function for on the subsequent pass. After processing all of the values, the return value of this function will be the return value of reduce(). This function will always be passed four arguments:
    1. previousValue:
      The value previously returned in the last invocation of the accumulator, or opt_initial, if supplied (see below).
    2. currentValue:
      The current value being processed.
    3. currentIndex:
      The index of the current value being processed.
    4. arrOrObj:
      The array (or array-like object) or object whose values are being traversed.
  3. opt_initial {?}:
    Optional. Defaults to the first value found in arrOrObj. The value to use as the first argument in the first call to accumulator.

Returns

If arrOrObj doesn't contain any values but opt_initial was specified, opt_initial will be returned. If arrOrObj only contains one value and opt_initial wasn't specified, that value will be returned. If multiple values are processed, the return value will be that of the last invocation of accumulator().