How to Filter a Map in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

banner

Photo by Lane Jackman

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee