Map Method
Today yet another great array method, following reduce() and filter() , there is map().
The Map()
method is a data structure that we can use to map values
to `keys
, So just like objects where data is stored in key-value
pairs in maps.
The big difference between objects
and maps
is that in maps the keys
can have any type ie: it can be arrays, boolean, and any type.
Now let's get our hands dirty by writing some code,
// The easiest way to fill the map with empty values
const friends = new Map();
// Now we can use the set method to pass in the values
friends.set('name', 'Kaarthik');
The above set method is similar to add
method in set. As I said before we can add any dataType as key
.
// Any datatype (Setting up my two favourite country )
friends.set(1, `India`);
friends.set(1, `Italy`);
friends.set(true, `Yes I'm allowed to drive a car`)
In order to read the values, we use the get
method and it is available on all maps.
console.log(friends.get(`name`)) // Kaarthik
Apart fromget
and set
we have one more method called has
which returns a boolean indicating whether an element with the specified key exists or not.
console.log(friends.has(`name`)) // true
we can also delete elements based on the key using the delete
method,
friends.delete(`name`)
We can also clear the whole map by using the clear
method,
friends.clear()
Iteration in Maps
JavaScript's Map object has a handy function, forEach()
, which operates similarly to arrays' forEach()
function. JavaScript calls the forEach()
callback with 3 parameters: the value, the key, and the map itself.
const map = new Map();
map.set('greeting', 'Hello');
map.set('name', 'John');
map.forEach((value, key, map) => {
// Prints "greeting Hello" followed by "name John"
console.log(value, key);
});
Map entries()
JavaScript maps don't have chainable helpers like filter()
or map()
for arrays. If you want to use filter()
with a map, you should use Map entries()
to first convert the map to an iterator, and then use the the spread operator or the Array.from()
function to convert the iterator to an array.
const map = new Map();
map.set('greeting', 'Hello');
map.set('name', 'John');
// [['greeting', 'Hello'], ['name', 'John']]
[...map.entries()];
// [['greeting', 'Hello'], ['name', 'John']]
Array.from(map.entries());
// Equivalent since `entries()` is the default iterator
[...map]; // [['greeting', 'Hello'], ['name', 'John']]
// First convert map into an array of entries, then you can use `filter()`
[...map.entries()].filter(([key, value]) => value.length > 4); // [['greeting', 'Hello']]
If you need only the map keys and values then you can use map.keys()
& map.values()
Array.from(map.keys()); // ['greeting', 'name']
Array.from(map.values()); // ['Hello', 'John']
Thanks for reading my blog & Let's connect! ๐๐ผ
Follow me for more similar articles :D
Feel free to subscribe to my Youtube Channel & Follow me on Twitter <3