Code Premix

How to use Map, Filter, and Reduce in JavaScript

📅June 15, 2021

Today we will give you an understanding of the map(), filter() and reduce() operators in JavaScript. These three operators are very useful in JS development.

const products = [
  {
    "name": "product 1",
    "size": "small",
    "weight": 50
  },
  {
    "name": "product 2",
    "size": "small",
    "weight": 100
  },
  {
    "name": "product 3",
    "size": "medium",
    "weight": 150
  },
  {
    "name": "product 4",
    "size": "big",
    "weight": 500
  }
]

Understanding of the Map, Filter and Reduce functions

  1. Map Operator
  2. Filter Operator
  3. Reduce Operator

1. Map Operator

If I already have an array and I want to do the exact same operation on each of the elements in the array and return the same amount of items in the array, use the map.

let product_list = products.map((product, index, products) => {
  return product.name
});
// Output: ["product 1", "product 2", "product 3", "product 4"]

In the above example we will have an array of product names.

2. Filter Operator

If I already have an array but I only want to have items in the array that match certain criteria, use the filter.

let small_products = products.filter((product, index, products) => {
  return product.size === "small"
});
// Output: [{"name":"product 1","size":"small","weight":50},{"name":"product 2","size":"small","weight":100}]

3 Reduce Operator

If I already have an array, but I want to use the values in that array to create something completely new, use the reduce.

let total_weight = products.reduce((weight, product, index, products) => {
  return weight += product.weight
}, 10);
// Output: 810

Let’s take the understanding of the parameters. Reduce function has two major parameters.

  • The first parameter is the callback function and the second parameter is initial value.
  • The callback function has four parameters.
    • The first parameter is the initial value or the previously returned value of the function. In our case it’s 10. You can set any value as per your requirement.
    • The second parameter is the current element in the array.
    • The third parameter is the index of the current element.
    • The last is the full array.

Note: If you are not define the initial value then by default it will consider the first element of an array as a initial value.

Thank you for reading. Happy Coding!