DEV Community

loading...

How to create your own reduce 😎

wakeupmh profile image Marcos Henrique ・1 min read

What is it?


The reduce, oh the reduce.
So spoken but so little understood.

Well, reduce() started to become popular with ES6, along with the map() and filter() functions that recalled the javascript functional footprint.
Okay, what is it for?
As the name suggests, reduce seeks to reduce an array.

It will iterate through each element of this list in order to ultimately generate a single value (of any type), such as the sum of all elements in this array.

Remembering that we are not just stuck with numbers.

Normal reduce:

const nums = [1,2,3,4,5,6,7,8,9];
console.log(nums.reduce((acc, act) => return acc+act;)

Let's create our own reduce 🀩

Array.prototype.myReduce = (callback, initialValue) =>{
    const initialIndice = initialValue ? 0 : 1
    let acc = initialValue || this[0]

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

    return acc;
}

const sum = (total, value) => total + value;
const nums = [1,2,3,4,5,6,7,8,9];
console.log(nums.myReduce(sum, 0))

That's all folks

Discussion

pic
Editor guide
Collapse
evanplaice profile image