Implenting Array.reduce() Method from scratch

·

1 min read

// normal
arr.reduce(callbackfn, initialValue);
// callback function with parameters
// initialValue maybe 0 or whatever you can give 
arr.reduce((previousValue, currentValue, currentIndex, array) => {
const nextValue = previousValue + currentValue;
return nextValue;
}, initialValue);

Array.reduce() accepts a callback function and initial value as an input and which is obviously optional , so this function will be called for each elementof the array with the initial value at the beginning and then with the value returned from last call of same function as the above code you are seeing

This callback function has 4 parameters (previousValue , currentValue , currentIndex , array)

By this array.reduce() we can do aggregation , seggregation and many other things

Implementing array.reduce() from scartch

Array.prototype.myReduce = function(callback, initialValue) {
  // Check if the array is empty
  if (this.length === 0) {
    if (initialValue === undefined) {
      throw new TypeError('Reduce of empty array with no initial value');
    } else {
      return initialValue;
    }
  }

  // Initialize accumulator with initialValue or first element of the array
  let accumulator = initialValue === undefined ? this[0] : initialValue;

  // Start iterating from the second element if initialValue is provided, otherwise from the first
  for (let i = initialValue === undefined ? 1 : 0; i < this.length; i++) {
    accumulator = callback(accumulator, this[i], i, this);
  }

  return accumulator;
};