We can filter a map in JavaScript in three distinct ways: forEach()
, filter()
, and for...of
loops.
Filtering with forEach()
Method:
The forEach()
method is a fundamental approach to iterate over a Map and selectively delete elements based on a specified condition.
const map1 = new Map([
['num1', 1],
['num2', 2],
['num3', 3],
]);
map1.forEach((value, key) => {
if (value > 1) {
map1.delete(key);
}
});
// Result: {'num1' => 1}
console.log(map1);
This method, driven by a callback function, operates on each key-value pair of the Map, checking conditions and modifying the Map accordingly.
Alternative Approach: Using filter()
Method:
Converting a Map to an array and using the filter()
method provides an alternative perspective on Map filtering.
const map1 = new Map([
['num1', 1],
['num2', 2],
['num3', 3],
]);
const filtered = new Map(
Array.from(map1).filter(([_key, value]) => value > 1),
);
// Result: {'num2' => 2, 'num3' => 3}
console.log(filtered);
This approach involves array conversion, destructuring assignment, and filtering using the filter()
method.
Explore with for...of
Loop:
Filtering a Map using a for...of
loop offers a classic yet readable solution.
const map1 = new Map([
['num1', 1],
['num2', 2],
['num3', 3],
]);
const filtered = new Map(
Array.from(map1).filter(([_key, value]) => value > 1),
);
// Result: {'num2' => 2, 'num3' => 3}
console.log(filtered);
This loop, designed for iterable objects, simplifies the process of iterating over a Map and selectively deleting elements.
Test Your Understanding:
Before we conclude, let’s reinforce your knowledge with a practice question:
Given a Map originalMap
containing key-value pairs, write a function filterMapGreaterThanN
that filters out all entries where the corresponding values are greater than a given threshold n
. The function should return a new Map with the filtered entries.
// Sample Map
const originalMap = new Map([
['num1', 5],
['num2', 8],
['num3', 3],
['num4', 12],
]);
// Function to filter Map entries
function filterMapGreaterThanN(inputMap, n) {
// < < < Your code here > > >
}
// Test the function
const filteredMap = filterMapGreaterThanN(originalMap, 7);
// Expected Result: {'num2' => 8, 'num4' => 12}
console.log(filteredMap);
Please attempt before seeing the Answer:
function filterMapGreaterThanN(inputMap, n) {
// Use the filter() method along with Array.from() to create a new Map
const filteredMap = new Map(
Array.from(inputMap).filter(([_key, value]) => value > n)
);
return filteredMap;
}
Conclusion:
In this technical guide, we explored three detailed methods for filtering a Map in JavaScript: forEach()
, filter()
, and for...of
loops. As you master these techniques, remember that efficient Map filtering is a crucial skill in your JavaScript toolkit.