Understanding JavaScript Map Methods
JavaScript Map Methods Creating a Map with new Map() To construct a map in JavaScript, you can pass an array to the constructor: Accessing Values with Map.get() Retrieve the val...
JavaScript Map Methods
Creating a Map with new Map()
To construct a map in JavaScript, you can pass an array to the new Map() constructor:
let myMap = new Map([['key1', 'value1'], ['key2', 'value2']]);
Accessing Values with Map.get()
Retrieve the value associated with a specific key in a map using the get() method.
let value = myMap.get('key1');
Adding and Modifying Entries with Map.set()
Add new elements or update existing ones in a map using the set() method:
myMap.set('key3', 'value3');
myMap.set('key1', 'newValue1');
Determining the Size with Map.size
The size property provides the count of elements present in a map:
let numberOfEntries = myMap.size;
Removing Elements with Map.delete()
Remove a specific element from a map using the delete() method:
myMap.delete('key2');
Clearing All Elements with Map.clear()
To remove all entries from a map, use the clear() method:
myMap.clear();
Checking for a Key with Map.has()
The has() method checks if a particular key exists in a map and returns true if it does:
let hasKey = myMap.has('key1');
Iterating with Map.forEach()
Execute a callback for each key/value pair in a map using the forEach() method:
myMap.forEach((value, key) => {
console.log(key, value);
});
Accessing Entries with Map.entries()
The entries() method returns an iterator object with [key, value] pairs in a map:
for (let entry of myMap.entries()) {
console.log(entry);
}
Retrieving Keys with Map.keys()
Get an iterator object containing the keys in a map using the keys() method:
for (let key of myMap.keys()) {
console.log(key);
}
Obtaining Values with Map.values()
The values() method provides an iterator object with the values in a map:
for (let value of myMap.values()) {
console.log(value);
}
Using Objects as Keys
A key feature of maps is the ability to use objects as keys. Remember, the key is an object, not a string:
let objKey = {};
myMap.set(objKey, 'value');
JavaScript Map.groupBy()
Introduced in ES2024, the Map.groupBy() method groups elements of an object based on string values returned from a callback function. This method does not alter the original object.
Browser Support for Map.groupBy()
The Map.groupBy() feature is part of ECMAScript 2024 and is supported in newer browser versions, including:
- Chrome 117
- Edge 117
- Firefox 119
- Safari 17.4
- Opera 103
Comparing Object.groupBy() and Map.groupBy()
The main difference is that Object.groupBy() groups elements into a JavaScript object, whereas Map.groupBy() groups elements into a Map object.