Borislav Hadzhiev
Sat Nov 13 2021·2 min read
Photo by Lane Jackman
Use the forEach()
method to filter a Map
in JavaScript. The method gets
called with each key-value pair in the Map
, where we can check for a condition
and use the delete()
method to delete any of the Map
elements we want to
filter out.
const map1 = new Map([ ['num1', 1], ['num2', 2], ['num3', 3], ]); map1.forEach((value, key) => { if (value > 1) { map1.delete(key); } }); // 👇️ {'num1' => 1} console.log(map1);
We used the Map.forEach method to iterate over the Map object.
The function we passed to the forEach()
method gets called for each key-value
pair of the Map
and gets passed the following parameters:
value
- the value of the iterationkey
- the key of the iterationmap
- the Map
objectWe make use of the value
to check for a condition and of the key
to
delete
any of the elements we don't need in the Map
.
An alternative approach is to convert the Map
method to an array and use the
filter
method.
To filter a Map
in JavaScript:
Map
to an array.filter()
method to iterate over the array.Map
.const map1 = new Map([ ['num1', 1], ['num2', 2], ['num3', 3], ]); const filtered = new Map( Array.from(map1).filter(([key, value]) => { if (value > 1) { return true; } return false; }), ); // 👇️ {'num2' => 2, 'num3' => 3} console.log(filtered);
We used the Array.from
method to convert the Map
into an array of key-value
pairs.
const map1 = new Map([ ['num1', 1], ['num2', 2], ['num3', 3], ]); // 👇️ [['num1', 1], ['num2', 2], ['num3', 3]] console.log(Array.from(map1));
When we convert the Map
to an array, we get back a two-dimensional array, on
which we can call the filter
method.
The first element in each sub-array is the key, and the second - the corresponding value.
We use
destructuring assignment
to destructure the key and value in the callback function we passed to the
filter
method.
const [key, value] = ['num1', 1]; console.log(key); // 👉️ num1 console.log(value); // 👉️ 1
In the callback function we check for a condition and return true
if the
condition is met and false
otherwise.
The filter
method returns a new array containing only the elements, for which
the callback function returned a truthy value.
The last step is to convert the array back to a Map
using the
Map()
constructor.