loading...
Cover image for JS / creating our own map, reduce, and filter functions

JS / creating our own map, reduce, and filter functions

icncsx profile image DH Kim ・2 min read

Map, reduce, and filter are some of the most frequented array methods in the JavaScript developer's toolbox. Interestingly enough, they share many similarities. I can list three off the top of my head. First, they will iterate over an array and perform a computation. Second, they will return a new array. And third, they are pure functions (πŸ˜ƒ). In this post, I want to show you how we can implement our own map, reduce, and filter method.

Map

The map method is used for creating a new array from an existing one. The method iterates through the array and applies a callback function to each element.

const myMap = (arr, cb) => {
    const newArr = [];
    for (const el of arr) {
        newArr.push(cb(el));
    }
    return newArr;
}

That's really all there is to the map method. Make sure to initialize a new empty array because we don't want to mutate the existing array.

Filter

The filter method applies a conditional statement to each element in an array. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

const myFilter = (arr, cb) => {
    const newArr = [];
    for (const el of arr) {
        if (cb(el)) {
            newArr.push(el);
        }
    }
    return newArr;
}

That wasn't too bad right?

Reduce

The reduce method is aptly named because it reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array. Per MDN: "At each iteration, the reducer returns a value which is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value."

const myReduce = (arr, cb, initialValue) => {
    let acc = initialValue;

    for (const el of arr) {
        acc = cb(acc, el);
    }

    return acc;
}

That's it! We've just implemented our own map, reduce and filter function, and we did it in less than 100 lines. Hurrah (😁)! Fun fact: I published my own version of Lodash because I thought re-creating the wheel would help me understand how JavaScript's built-in methods work. I think I learn better if I re-create the wheel... How do you like to learn?

Warmly,
EK

Posted on by:

icncsx profile

DH Kim

@icncsx

Software engineer interested in cloud computing and serverless backend services.

Discussion

markdown guide