Categories
JavaScript Answers

How to filter a JavaScript Map?

Spread the love

Sometimes, we want to filter a JavaScript Map.

In this article, we’ll look at how to filter a JavaScript Map.

How to filter a JavaScript Map?

To filter a JavaScript Map, we convert it to an array.

For instance, we write

const map0 = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3],
]);

const map1 = new Map([...map0].filter(([k, v]) => v < 3));

console.info([...map1]);

to create a map with the Map constructor.

Then we convert it to an array with the spread operator.

And then we call filter with a function that checks if value v is less than 3.

We use the returned array to create another Map.

Conclusion

To filter a JavaScript Map, we convert it to an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *