Title : How to Filter a Map in JavaScript (Enhance Version)
In JavaScript, you can filter a Map using the Map.prototype.entries()
method along with the Array.prototype.filter()
method. Here are five examples that demonstrate how to filter a Map in different scenarios:
Example 1: Filtering by Key
const originalMap = new Map([
['apple', 10],
['banana', 5],
['orange', 15],
['grape', 8]
]);
const filteredMap = new Map(
[...originalMap.entries()].filter(([key, value]) => key !== 'banana')
);
console.log(filteredMap);
Explanation:
- We create a
Map
calledoriginalMap
with some key-value pairs. - Using
[...originalMap.entries()]
, we convert the Map into an array of key-value pairs. - We use
Array.prototype.filter()
to exclude the pair where the key is 'banana'. - Finally, we create a new
Map
from the filtered array and log the result.
Example 2: Filtering by Value
const originalMap = new Map([
['apple', 10],
['banana', 5],
['orange', 15],
['grape', 8]
]);
const filteredMap = new Map(
[...originalMap.entries()].filter(([key, value]) => value > 8)
);
console.log(filteredMap);
Explanation:
- We filter the Map based on the value, keeping only those pairs where the value is greater than 8.
Example 3: Filtering by a Custom Condition
const originalMap = new Map([
['apple', { quantity: 10, color: 'red' }],
['banana', { quantity: 5, color: 'yellow' }],
['orange', { quantity: 15, color: 'orange' }],
['grape', { quantity: 8, color: 'purple' }]
]);
const filteredMap = new Map(
[...originalMap.entries()].filter(([key, value]) => value.quantity > 8)
);
console.log(filteredMap);
In this example, the Map contains objects as values. We filter based on a custom condition, selecting only those pairs where the quantity
property of the value is greater than 8.
Top comments (0)