This post will discuss how to filter a map in JavaScript.

Filtering a map means creating a new map or updating the existing map to contains only the key-value pairs that satisfy a certain condition. Here are some of the methods we can use to filter a map in JavaScript:

1. Using Array.filter() function

The Array.filter() function creates a new array with only the elements that pass a test function. The spread operator (…) or Array.from() function converts a map into an array of [key, value] pairs. We can use these functions together to create a new array of [key, value] pairs that meet the condition, and then convert it back to a map using the Map() constructor. The following code illustrates this:

Download  Run Code

2. Using Map.forEach() and Map.delete() function

The Map.forEach() function iterates over the key-value pairs in the map and executes a callback function for each pair. The Map.delete() function removes a key-value pair from the map by its key. We can use these functions together to delete the key-value pairs that do not meet the condition from the original map. The following code illustrates this:

Download  Run Code

That’s all about filtering a map in JavaScript.