In this article we will learn how to filter a map.
It is very common to filter a map in JavaScript.
Problem
Now we have a problem, which is that we want to filter the map.
Imagine that we have a map with a set of numbers like this:
// Map
new Map([
["one", 50],
["two", 100],
["three", 150],
["four", 200]
]);
// Map(4) { 'one' => 50, 'two' => 100, 'three' => 150, 'four' => 200 }
And we want to delete the numbers above 100 to make it like this.
new Map([
["one", 50],
["two", 100],
]);
// Map(2) { 'one' => 50, 'two' => 100 }
How to solve this problem
Well, to solve this problem there is more than one solution:
- Using
forEach
. - Using
filter
Filter a map using forEach
We can use forEach
to filter our map.
// 1. Define a map
const map = new Map([
["one", 50],
["two", 100],
["three", 150],
["four", 200]
]);
// 2. Iterate over map
map.forEach((value, key) => {
// 3. If value > 100
if (value > 100) {
// 4. Delete element
map.delete(key);
console.log(`Deleted ${value}`);
}
});
// 5. Print result:
console.log(map);
Output
Deleted 150
Deleted 200
Map(2) { 'one' => 50, 'two' => 100 }
We used the forEach
method to iterate over the Map object.
Filter a map using filter
method
We can use filter
to filter our map as well.
Example
// 1. Define a map
const map = new Map([
["one", 50],
["two", 100],
["three", 150],
["four", 200]
]);
// 2. Create new map
const filter = new Map(
// 3. Filter our map
Array.from(map).filter(([key, value]) => {
// 4. If value more than 100
if (value > 100) {
// Don't add it to new map
return false
}
// Otherwise add it to new map
return true;
})
)
// Result:
console.log(filter);
Output
Map(2) { 'one' => 50, 'two' => 100 }
How it works?
- First, we defined our map
const map
- Second, we defined a new map
const filter
- Third, we filter our map using
filter
method - Then, we check if value is more than
100
or not
// 4. If value more than 100
if (value > 100) {
// Don't add it to new map
return false
}
// Otherwise add it to new map
return true;
- If value more than 100, don't add it into new map
- Otherwise add it.
Thank you for reading
Thank you for reading my blog. 🚀