DEV Community

Cherag Verma
Cherag Verma

Posted on

Polyfill for Array.reduce() Javascript

Just wrote a code for polyfill reduce() in JavaScript, thought I will share it will you all.

Array.prototype.myReduce = function(fn, initial) {
    let values = this;

    values.forEach(item => {
        initial = initial !== undefined ? fn(initial, item) : item
    })

    return initial;
}

Using the above

var values = [2, 5, 5]
values.reduce((a, b) => a * b)  // 50
values.myReduce((a, b) => a * b)  // 50

I have dry tested it for multiple outputs. Do let me know if there can be any improvements.

Cheers!

Top comments (7)

Collapse
 
melvdouc profile image
Melvin DOUCET • Edited

I'm sorry but it doesn't make any sense to use forEach in a polyfill as a browser that doesn't support reduce is unlikely to support forEach as well. Same thing goes for the let keyword.

if (!Array.prototype.reduce) {
Array.prototype.reduce = function(cb, acc) {
var i = 0;
if (acc === void 0) {
acc = this[0];
i = 1;

}
for (; i < this.length; i++) {
var newAcc = cb(acc, this[i], i, this);
if (newAcc === undefined)
continue;
acc = newAcc;
}
return acc;
}
};

Collapse
 
ad99526 profile image
Abhishek Dubey

Would not work for undefined acc

Collapse
 
c4r4x35 profile image
Srinivas Kandukuri

It's almost same, Incase if anyone wants in simple form

Array.prototype.myReduce = function (callback, initialValue) {
let accumulator = initialValue === undefined ? undefined : initialValue;
for (let i = 0; i < this.length; i++) {
if (accumulator != undefined)
accumulator = callback(this[i], i, this)
else
accumulator = this[i];
}
return accumulator;
}

Collapse
 
melvdouc profile image
Melvin DOUCET • Edited

let accumulator = initialValue === undefined ? undefined : initialValue;

In other words:
let accumulator = initialValue;

Collapse
 
sagar profile image
Sagar

thanks for posting the polyfill of the reducer. it will help me to crack interviews.

Collapse
 
surajpandey186 profile image
Suraj Bhushan Pandey

Array.prototype._reduce = function (callback, initial) {

if (initial) {
    previous = initial;

   for (let i = 0; i < this.length; ++ i) {
      previous = callback(previous, this[i], i, this)
   }

} else {
    previous = this[0]
    for (let i = 1; i < this.length; ++ i) {
        previous = callback(previous, this[1], i, this)
    }
}
return previous
Enter fullscreen mode Exit fullscreen mode

}

Collapse
 
amansaxena001 profile image
Amansaxena001

in else part it should be this[i+1] not this[1]