How To Filter A Map In JavaScript

How to Filter a Map in JavaScript

Let’s read this article to know how to filter a map in JavaScript. The following are ways to iterate over map elements in JavaScript, like using the forEach() method and for…of loop. Let’s go into detail.

How to filter a map in JavaScript

Map in JavaScript is an object type that allows for storing key-value data.

At first glance, the map looks like an ordinary object. But it is not natural for people to create more map data types. The map has distinct characteristics compared to ordinary objects. Here, let’s learn about map in JavaScript!

A map in JavaScript is a data structure that allows storing data in a key-value fashion, similar to an object. However, they differ in that:

  • Object only allows using String or Symbol as key.
  • The map allows any data type (String, Number, Boolean, NaN, Object,…) can be key.

Using forEach() method

A map is an iterable object. Therefore, you can use the forEach() method to filter the elements of the map.

Syntax:

forEach((value, key, map) => { } )

Parameters:

  • value: the value of each iteration
  • key: the key of each iteration
  • map: the map being iterated

Code sample:

let map = new Map([
    [13, 'one'],
    [21, 'two'],
    [3, 'three'],
    [45, 'four']
]);

//iterate over each pair of values in map by forEach() method
map.forEach((value, key, map)=>{
    if(key > 10)
    console.log(key, value);
})

Output

13 'one'
21 'two'
45 'four'

We use the forEach() method to iterate each key-value pair. If the map key meets the condition, execute the console.log command.

Using for…of loop

The for…of loop was introduced in ES6. Similar to for, this loop is used to traverse each element of the traversal object. The number of iterations equals the number of elements of the object.

Code sample:

let map = new Map([
    [13, 'one'],
    [21, 'two'],
    [3, 'three'],
    [45, 'four']
]);

//the for…of loop filter out each key-value pair to check the condition
for(let [key, value] of map){
    if(key > 10)
    console.log(key, value);
}

Output

13 'one'
21 'two'
45 'four'

We can see the syntax of for...of is more explicit and easier to understand than the forEach() method.

Summary

Above, I showed you how to filter a map in Javascript using two straightforward and short methods. I hope it will be helpful to you. Don’t hesitate to leave comments in the comment section to complete and deepen your knowledge. And let’s learn more about Javascript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *