Javascript Array customReduce(reducer, initialValue)

Description

Javascript Array customReduce(reducer, initialValue)


Array.prototype.customReduce = function (reducer, initialValue) {
  let arr = this;
  let acc = initialValue;

  arr.forEach(function (value, index) {
    if (acc !== undefined) {
      acc = reducer(acc, value, index, arr[index], arr);
    } else {/*w w w  . ja  va 2s  .  co  m*/
      acc = value;
    }

  });

  return acc;
};

[1, 2, 3, 4].customReduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 5);



PreviousNext

Related