Map, Filter, Reduce in JavaScript Explained

Hello programmers, In this article, you will learn about JavaScript array methods that were introduced in ES5. These are map(), filter(), reduce().

After the introduction of these methods, the way programmers used to write code in JS changed a lot. These solves the specific problem which earlier used to take many lines of codes. We will discuss each of them with examples.

map()

The JavaScript map() method iterates over an array and applies provided function on each of the elements of the array and returns a new array.
Let me show you an example.

const arr = [1, 2, 3, 4];

const newArr = arr.map((val, idx, arr) => {
    return val * 3;
});

console.log(newArr);
output : [ 3, 6, 9, 12 ]

Here you can see map function takes a callback function as its argument. The callback function takes three arguments, the first one is the value of the element of the array, second is its index and third is the array itself. It then returns the value of the element multiplied by 3 in a new array and is stored in a variable “newArr”.

filter()

As the name suggests filter() function filter out elements from an array that satisfies a given condition. The condition is passed as a callback function and is either evaluated as true or false. If it evaluates to true then the element is pushed into the new array. Below is an example of the same.

const arr = [1, 2, 3, 4];

const newArr = arr.filter((val, idx) => {
    return val > 2;
});

console.log(newArr);
output: [ 3, 4 ]

Here if the element value is greater than 2 then the callback function returns true and the element gets pushed into the new array.

reduce()

The reduce method is probably the most complex method among the three. It simplifies the array and reduces it to a single value. Suppose you have to find the sum of all elements of the array then you will just pass a variable “accumulator” and a callback function that updates the accumulator. Let’s have a look at the code to get a better insight.

const arr = [1, 2, 3, 4];

const res = arr.reduce((acc, val, idx, arr) => {
    return (acc += val);
}, 0);

console.log(res);
output : 10

Here reduce function takes a callback function as its argument which takes 4 variables as its argument, the accumulator, element value, index, and the array respectively. Of course, you can skip a few of them if you don’t want them. It then takes an initial value of accumulator and updates the accumulator as described in the callback function.

Hope you got a better insight about these, after reading this article.

You may also learn,

Leave a Reply

Your email address will not be published.