Accumulating some value over using a callback function and initial value in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array a callback function and an initial value.

The function should accumulate a value over the iteration of array and finally return the value just like the Array.prototype.reduce() does.

Example

Following is the code −

 Live Demo

const arr = [1, 2, 3, 4, 5];
const sum = (a, b) => a + b;
Array.prototype.customReduce = function(callback, initial){
   if(!initial){
      initial = this[0];
   };
   let res = initial;
   for(let i = initial === this[0] ? 1 : 0; i < this.length; i++){
      res = callback(res, this[i]);
   };
   return res;
};
console.log(arr.customReduce(sum, 0));

Output

Following is the console output −

15
raja
Published on 17-Apr-2021 11:25:24
Advertisements