DEV Community

Marcos Henrique
Marcos Henrique

Posted on

How to create your own reduce 😎

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;)
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

That's all folks

Discussion (1)

Collapse
evanplaice profile image
Evan Plaice

Nice! Gif