DEV Community

shazz
shazz

Posted on

This thing about JS Reducer

Hello,

Shouting out to anyone who is well versed with JS and can help me with this query.

Can anyone tell me why the Reducer method in Javascript is called 'Reducer', when it exactly does the opposite...doing additions in array.

I searched online for the answer but did not find any and this particular question is driving me crazy.

Thanks for the advance help.

@shazz

Top comments (2)

Collapse
 
dinsmoredesign profile image
Derek D • Edited

The reducer takes a collection (array) of inputs and reduces it to one output.

Collapse
 
aminnairi profile image
Amin • Edited

Actually, you don't have to return a single output.

You can totally re-define the other popular array functions like map, filter etc... Only with reduce.

"use strict";

const map = (callback, array) => {
    return array.reduce((accumulator, element) => {
        return [...accumulator, callback(element)];
    }, []);
};

const filter = (predicate, array) => {
    return array.reduce((accumulator, element) => {
        if (predicate(element)) {
            return [...accumulator, element];
        }

        return accumulator;
    }, []);
};
Enter fullscreen mode Exit fullscreen mode

As for the question, my guess (because I could not find enough answers except for this stackoverflow question) is that it is called like that (or fold, or aggregate) because as I said, you can actually use reduce to define all sort of array methods with it.

And I guess the term is representing pretty well all sorts of operations that are possible to do with it. But whether you call it reduce or fold or aggregate, it won't match 100% what you are trying to do at the moment, because some times you are filtering, some times you are mapping, etc...

It is a tradeoff term I guess and most of the time, you won't be using reduce to map, since there is already a definition of the map method. Same thing for filter and the other methods.