DEV Community

loading...

Polyfill for Array.reduce() Javascript

cheragv profile image 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 (1)

pic
Editor guide
Collapse
sagar profile image
Sagar

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