Getting to know map(), filter() and reduce() in JavaScript

Ronaldo B.July 27, 20227 min read

In this article

Manipulating arrays is one of the most repetitive tasks we perform when working with JavaScript. And there are three well-known methods that help us with this manipulation: map(), filter(), and reduce(). They are known methods, but we don't always remember the purpose of each one.

In this article, we will discuss the differences between these methods and in which situations they can help us.

These methods have a more concise and readable syntax and allow us to accomplish in a few lines what we would need to do with other loop methods, such as the forEach() method, for example. Let's now look at the definitions of these methods!

map() - Executes a function on all items of an array

The map() method aims to execute a function on each item of an array. This statement might lead us to ask: “But isn’t that what forEach() does?” Indeed, forEach() also manipulates the data of an array. However, there is a difference.

The map() method returns a new array after the manipulation, meaning it does not overwrite the original array. In fact, all methods we will learn about in this article return a new array as a response.

Moreover, the map() method has better performance than forEach(). Let’s see an example where using map() allows us to make a change to the data quite simply.

Imagine we have a list of products being displayed on our page, and we want to add a 10% discount to the prices of these products. How could we do this with map()? We could have an array of prices, like the one below:

const productsPrices = [100, 150, 300];

Then, we could call the map() method and store its return in a new variable, named productsDiscount, like this:

const productsDiscount = productsPrices.map(price => {
  return price * 0.9;
});

Note that it is necessary to define a return in the method for it to work. Without the return, the new array would have all its values as undefined.

Since our method only returned the price value, we could simplify this code even further, defining it in a single line:

const productsDiscount = productsPrices.map(price => price * 0.9);

Now, if we define a console.log() for the old variable and the new one, we will see the following result:

Result of our code

Excellent! The old array remains unchanged, but the new one has the discounts defined correctly.

In this example, we used an array of prices, but how could we do this with an object? Imagine we now have an array of objects, storing the information about our products:

const products = [{
  name: 'TV',
  price: 100
}, {
  name: 'Monitor',
  price: 150
}, {
  name: 'SSD',
  price: 300
}];

How could we apply the same 10% discount in this case? One solution is to use the Object.keys() method to find the indices of our products array and execute map() on these indices. Thus, we can change the key of the product object at each of its indices. Our code would look like this:

const productsDiscount = Object.keys(products).map(key => products[key]['price'] *= 0.9);

That way it would still work!

filter() - Filters an array

The next method we will discuss is filter(). As the name itself indicates, it aims to filter the information of an array. Its functionality consists of informing it of a condition. It will apply this condition to all items in our array, and those that meet the condition will be returned and added to the new output array. Thus, unlike what happens with map() and reduce(), filter() will always return true or false.

We might ask: “In what situations would I need to filter an array?” It is common to do this when we are removing an item from an array or filtering the results of a data array.

Let’s create an example of removing a record. Imagine we have an array of users with the following structure:

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

We just deleted the user with id equal to 2 and we want to remove it from the page. If we were using some JavaScript framework, like React, Angular, or Vue, we could update the page data without needing to refresh it. We could use this code:

const newUsers = users.filter(user => user !== 2);

The newUsers array will contain all users with an id different from 2. If we execute a console.log() for both variables, we will see the following result:

Result of the filter in our code

Note that the new array does not contain user 2, exactly what we wanted?

reduce() - Reduces an array into a single result

The reduce() method is very interesting and can be used when we want to perform some summation or when we want to merge several arrays into one. It reduces all values of an array into a single result based on the function we provide to it.

The first two parameters of this method are very important. The first represents the final result of the array reduction. This value is incremented throughout the reduce() process during each iteration of the loop. The second parameter involves the value of each index of the array. Let’s see an example to clarify this concept for us.

Imagine we have a variable that contains the semi-annual revenue information of a company. This array has the following structure:

const annualBilling = [1500, 1800, 700, 5000, 1600, 18000];

Now imagine that we want to know the total revenue during this period. We would need to add together each of the values in this array. The reduce() method could help us. To do this, we would simply add the previous total value in each iteration of the loop with the current revenue amount in each iteration. Our code would look like this:

const totalBilling = annualBilling.reduce((total, currentValue) => {

  return total + currentValue;

}, 0);

When we execute a console.log() for the totalBilling variable, we will see the following result:

Value of the sum of the array values

Very good! The sum was successfully completed. Note that the second parameter provided to reduce() was the number 0. This parameter represents from which number we want to start our summation operation. By default, this value is 0. Thus, we would not need to specify it in this case if we did not want to.

Using all methods together

These three methods are truly amazing. But if they are incredible on their own, imagine if we could use all three together! That is entirely possible! Since each of these methods returns a new array, we can then call another method afterward, performing what we might call a "method chaining of array methods".

Imagine that we have an array that stores the employees of our company. This array has the following structure:

const employees = [{
  name: 'Luke',
  department: 'Financeiro',
  salary: 1500
}, {
  name: 'Han',
  department: 'Financeiro',
  salary: 1200
}, {
  name: 'Ben',
  department: 'Marketing',
  salary: 2000
}, {
  name: 'Leia',
  department: 'Marketing',
  salary: 1750
}, {
  name: 'Rey',
  department: 'Financeiro',
  salary: 1000
}]

We want to know how much the Finance Department would receive in total if we gave them a 50% raise. To find out this information, we would need: 1) to filter the array for the employees in the Finance Department, 2) to add a 50% raise to their salaries and 3) to sum up those salaries. We could do this using the methods we learned in this article. Our code would look like this:

const totalSalary = employees.filter(employee => {

  return (employee.department === 'Financeiro');

}).map(item => {

  return item.salary *= 1.5;

}).reduce((total, currentValue) => {

  return total + currentValue;

});

When we execute a console.log() for the totalSalary variable, the following result would be returned:

Result of our code in the console

Excellent! We discovered the total value of this operation.

We used the "extended" way above, defining the return in each of the methods. However, as we have seen in this article, we can simplify this code, leaving it as follows:

const totalSalary = employees
    .filter(employee => (employee.department === 'Financeiro'))
    .map(item => item.salary *= 1.5)
    .reduce((total, currentValue) => total + currentValue);

Now that's much better!

Conclusion

In this article, we saw the difference between the map(), filter(), and reduce() methods. We even learned how to use these three methods together for a much simpler and more practical array manipulation.

You can learn much more about arrays and other fundamental concepts of JavaScript through our Complete JavaScript Course, where we teach the various concepts of this incredible language through amazing projects.

See you in the next article :)

Keep learning with Hcode

Sign up for the course platform and follow the next blog guides.