This post will discuss how to filter out the null values from a map in JavaScript.

Filtering out the null values from a map in JavaScript is a common task that can be done in different ways. Here are some examples:

1. Using Array.filter() function

If we have an object literal as a map, we can use the Object.entries() function to get an array of the key-value pairs, and then use the Array.filter() function to remove the pairs that have null values. However, this takes two iterations and an extra array to be created. The following code illustrates this:

Download  Run Code

 
This function will not modify the original map object, but creates an array of arrays. If we want to convert it back to an object or a Map, we can use the Object.fromEntries() function and Map() constructor, respectively. The following code illustrates this:

Download  Run Code

 
If we have a Map object as a map, we can use the Array.from() function to convert the map into an array of entries (key-value pairs) and use the Array.filter() function to remove the ones with null values. Then we can use the new Map() constructor to create a new map from the filtered array. For example:

Download  Run Code

2. Using Map.forEach() function

If we have a Map object as a map, we can use the Map.forEach() function to iterate over the key-value pairs and delete the ones that have null values. We can use the delete() function which takes a key as an argument and removes the key-value pair associated with that key from the map object. This will modify the original map in place, without creating a new one. The following code illustrates this:

Download  Run Code

 
We can also use a for…of loop to iterate over the entries of the map and use the Map.delete() function to remove any key that has a null value. For example:

Download  Run Code

3. Using a custom function

If we want a more generic and efficient way to filter null values from a map in JavaScript, we can use a custom function that takes a map as an argument and returns a new map with the filtered pairs. For example, the following function will return a new map without modifying the original one. It will also only iterate over the map’s entries once and avoid creating any extra arrays.

Download  Run Code

4. Using Lodash library

Lodash is a popular JavaScript library that provides numerous utility functions for working with various data structures. Lodash has a function called omitBy() that takes an object and a predicate function as arguments and returns a new object without the elements that satisfy the predicate function. This is opposite of the _.pickBy() function, which returns a new object containing elements satisfying the predicate function. We can use these function to filter out the null values from a map by passing it to the predicate function. For example:

Download Code

That’s all about filtering out the null values from a map in JavaScript.