DEV Community

loading...

Polyfill for Array.reduce() Javascript

Cherag Verma
・1 min read

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!

Discussion (2)

Collapse
srinivaskandukuri profile image
~#S*K#~

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
sagar profile image
Sagar

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