This post will discuss how to remove entries with null values from a Map in JavaScript.

To remove entries with null values from a map in JavaScript, we need to iterate through the map entries and delete the entries that have a null value. We can use different functions to do this, such as:

1. Using Map.forEach() function

The Map.forEach() function executes a callback function for each entry in the map. We can use this function to check the value of each entry and delete it if it is null. For example, we can use the following code snippet to remove entries with null values from a map:

Download  Run Code

 
Alternatively, we can use the for…of loop to access the key and value of each entry in the map and delete it if the value is null. For example, we can use the following code snippet to remove entries with null values from a map:

Download  Run Code

 
This is the simplest and most straightforward way, but it requires us to mutate the original map and use the delete operator. However, it does not work to create a new map without null values.

2. Using Array.filter() function

We can use the Array.from() function to convert the map into an array of entries and use the Array.filter() function to remove the ones with null values. 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. This approach is preferred to create a new map without null values, and prefer a more declarative and expressive style of coding. For instance:

Download  Run Code

3. Using a custom function

Use a custom function that takes a map as a parameter and returns a new map without null values. This is a more reusable and modular way, but it requires us to write and maintain our own function. For instance:

Download  Run Code

 
This method works well if we need more control over how the values are compared or to reuse the function for different maps. However, it does not work to modify the original map or to use a more concise or functional style of coding.

That’s all about removing entries with null values from a Map in JavaScript.