Filter a Map in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Create a map of names and ages const map = new Map([["Thomas", 25], ["Samuel", 30], ["Christopher", 15]]); // Define a condition function function isAdult([key, value]) { return value >= 18; } // Convert the map to an array and filter it by the condition const filteredArray = [...map].filter(isAdult); // Convert the filtered array back to a map const filteredMap = new Map(filteredArray); // The filtered map contains only the pairs that meet the condition console.log(filteredMap); // Map(2) { 'Thomas' => 25, 'Samuel' => 30 } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Create a map of names and ages const map = new Map([["Thomas", 25], ["Samuel", 30], ["Christopher", 15]]); // Define a condition function function isAdult(value, key, map) { return value >= 18; } // Iterate over the map and delete the pairs that do not meet the condition map.forEach((value, key, map) => { if (!isAdult(value, key, map)) { map.delete(key); } }); // The map now contains only the pairs that meet the condition console.log(map); // Map(2) { 'Thomas' => 25, 'Samuel' => 30 } |
That’s all about filtering a map in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)