This post will discuss how to remove entries from a map while iterating over it in JavaScript.

To remove entries from a map while iterating it in JavaScript, we need to use the Map.delete() function to delete the entries that meet a certain condition. We can use different functions to iterate over the map, such as:

1. Using Map.delete() function

We can use the Map.delete() function with the Map.forEach() function to remove entries from a map. The forEach() function executes a callback function for each key-value pair in the map, which can check if the current key-value pair meet some condition for removal. If they do, it can use the delete() function to remove the pair from the map. For example, we can use the following code snippet to remove entries with odd values from a map:

Download  Run Code

 
Alternatively, we can use the for…of loop to iterate over the map entries and delete the ones that meet a condition. For example, we can use the following code snippet to remove entries with specific key or value from a map:

Download  Run Code

2. Using Array.filter() function

The Array.from() function to convert the map into an array of key-value pairs. The Array.filter() function creates a new array with all elements that pass a test implemented by a callback function. By combining these two functions, we can convert the map to an array and use the filter() function to filter out the key-value pairs that meet some condition for removal. Then use the new Map() constructor to create a new map from the filtered array. This is a more functional and concise way, but it requires us to create two intermediate arrays and use arrow functions. For instance:

Download  Run Code

3. Using a custom function

Use a custom function that takes a map and a condition as parameters and returns a new map without the deleted entries. This is a more reusable and modular way, but it requires us to write and maintain our own function. For example, the following code create a custom function and removes entries with even values using it:

Download  Run Code

That’s all about removing entries from a map while iterating over it in JavaScript.