How to Filter a Map in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 13, 2021

banner

Photo from Unsplash

Filter a Map in JavaScript #

Use the forEach() method to filter a Map in JavaScript. The method gets called with each key-value pair in the Map, where we can check for a condition and use the delete() method to delete any of the Map elements we want to filter out.

index.js
const map1 = new Map([ ['num1', 1], ['num2', 2], ['num3', 3], ]); map1.forEach((value, key) => { if (value > 1) { map1.delete(key); } }); // 👇️ {'num1' => 1} console.log(map1);

We used the Map.forEach method to iterate over the Map object.

The function we passed to the forEach() method gets called for each key-value pair of the Map and gets passed the following parameters:

  1. value - the value of the iteration
  2. key - the key of the iteration
  3. map - the Map object

We make use of the value to check for a condition and of the key to delete any of the elements we don't need in the Map.

An alternative approach is to convert the Map method to an array and use the filter method.

To filter a Map in JavaScript:

  1. Convert the Map to an array.
  2. Use the filter() method to iterate over the array.
  3. Exclude the elements that don't match the condition.
  4. Convert the array back to a Map.
index.js
const map1 = new Map([ ['num1', 1], ['num2', 2], ['num3', 3], ]); const filtered = new Map( Array.from(map1).filter(([key, value]) => { if (value > 1) { return true; } return false; }), ); // 👇️ {'num2' => 2, 'num3' => 3} console.log(filtered);

We used the Array.from method to convert the Map into an array of key-value pairs.

index.js
const map1 = new Map([ ['num1', 1], ['num2', 2], ['num3', 3], ]); // 👇️ [['num1', 1], ['num2', 2], ['num3', 3]] console.log(Array.from(map1));

When we convert the Map to an array, we get back a two-dimensional array, on which we can call the filter method.

The first element in each sub-array is the key, and the second - the corresponding value.

We use destructuring assignment to destructure the key and value in the callback function we passed to the filter method.

index.js
const [key, value] = ['num1', 1]; console.log(key); // 👉️ num1 console.log(value); // 👉️ 1

In the callback function we check for a condition and return true if the condition is met and false otherwise.

The filter method returns a new array containing only the elements, for which the callback function returned a truthy value.

The last step is to convert the array back to a Map using the Map() constructor.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.