Skip to content
Polyfill for Array.prototype.reduce

Polyfill for Array.prototype.reduce

Write a polyfill for Array.prototype.reduce in JavaScript and take care of all edge cases below,

  • the accumulator is undefined, or the array is empty
  • a sparse array, where an array might have some empty values

🔗Array.prototype.reduce 🟢 Easy 🧩 Pattern – JavaScript Essentials

JavaScript Reduce Polyfill

/**
 * @template T, U
 * @param {(previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U} callbackFn
 * @param {U} [initialValue]
 * @return {U}
 */
Array.prototype.myReduce = function (callbackFn, initialValue) {
  const arr = this;
  let startindex = 0;
  let accumulator = initialValue;

  if (accumulator === undefined) {
    if (arr.length === 0) {
      throw new TypeError("Reduce of empty array with no initial value");
    }
    accumulator = arr[0];
    startindex = 1;
  }

  for (let i = startindex; i < arr.length; i++) {
    if (i in arr) {
      accumulator = callbackFn(accumulator, arr[i], i, arr);
    }
  }
  return accumulator;
};
Code language: JavaScript (javascript)
Back to Top