How to Filter a Map in JavaScript
Unlike arrays, JavaScript's Map object does not have a built-in .filter() method. However, you often need to filter a Map to create a new one containing only the entries that meet a specific condition.
This guide will teach you the modern, standard methods for filtering a Map. You will learn the recommended, immutable approach that creates a new Map, and the mutable approach that modifies the Map in place.
The Core Distinction: Creating a New Map vs. Modifying in Place
Before filtering, you must decide on your approach:
-
Immutable (Creating a New
Map): This is the recommended best practice. You create a brand newMapthat contains only the filtered entries. The originalMapis left completely unchanged. This leads to more predictable and less bug-prone code. -
Mutable (Modifying in Place): This involves directly deleting entries from the original
Map. This can be slightly more memory-efficient as it doesn't create a newMap, but it should be done intentionally, as it is a destructive operation.
Method 1 (Recommended): Creating a New, Filtered Map
The most readable and idiomatic way to create a new, filtered Map is to convert the Map to an array, filter the array, and then convert the result back into a Map.
The logic:
- Convert to an Array: Convert the
Map's entries into an array of[key, value]pairs. The spread syntax ([...myMap]) is the most concise way to do this. filter()the Array: Use the standardArray.prototype.filter()method to keep only the entries that meet your condition.- Create a New
Map: Pass the filtered array of pairs to thenew Map()constructor.
For example, we have a Map of scores and we want to create a new Map containing only the passing scores (e.g., scores greater than 70).
// Problem: How to create a new Map with only the passing scores?
const scores = new Map([
['Alice', 85],
['Bob', 65],
['Charlie', 92],
]);
Solution:
const scores = new Map([
['Alice', 85],
['Bob', 65],
['Charlie', 92],
]);
// Convert to an array, filter, and convert back to a Map
const passingScores = new Map(
[...scores].filter(([key, value]) => value > 70)
);
console.log(passingScores);
// Output: Map(2) { 'Alice' => 85, 'Charlie' => 92 }
// The original Map is not changed
console.log(scores);
// Output: Map(3) { 'Alice' => 85, 'Bob' => 65, 'Charlie' => 92 }
This one-liner is powerful, readable, and the standard functional approach.
Method 2: Modifying a Map in Place
If you have a specific reason to mutate the original Map, you should iterate over its entries and use the map.delete(key) method to remove the ones that do not meet your criteria.
The logic:
- Iterate over the
Mapusing afor...ofloop orforEach(). - Inside the loop, check each entry against your condition.
- If an entry should be removed, call
map.delete(key).
Solution:
const scores = new Map([
['Alice', 85],
['Bob', 65],
['Charlie', 92],
]);
for (const [key, value] of scores) {
// If the score is NOT a passing score, delete the entry
if (value <= 70) {
scores.delete(key);
}
}
console.log(scores);
// Output: Map(2) { 'Alice' => 85, 'Charlie' => 92 }
Important: This method mutates the original Map. This can be useful for memory efficiency with very large Maps, but it's a destructive operation that should be used with care.
Conclusion: Which Method Should You Use?
The choice between these methods is a decision between immutability and mutability.
- You should almost always prefer the immutable approach by creating a new, filtered
Map. Thenew Map([...myMap].filter(...))pattern is the modern, safe, and recommended best practice for its clarity and predictability. - Use the mutable
for...ofloop withmap.delete()only when you have a specific, intentional reason to modify the originalMapin place, such as for performance optimizations on very large data sets.