DEV Community

Discussion on: This thing about JS Reducer

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.