DEV Community

Marcos Henrique
Marcos Henrique

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
evanplaice profile image
Evan Plaice

Nice! Gif

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️