Map and Set are two JavaScript knowledge buildings you should utilize to retailer a group of values, much like Objects and Arrays. They are specialised knowledge buildings that may make it easier to retailer and manipulate associated values.
In this tutorial, we are going to see how Map and Set work intimately and when to make use of them. We will even discover the Set object composition strategies that had been lately added to the JavaScript normal.
Table of Contents
The Map Object Explained
The Map
object shops knowledge in a key/worth pair construction, identical to an Object. The predominant variations between a daily object and a Map
are:
- A
Map
can have any kind of knowledge as the important thing worth - A
Map
maintains the order of knowledge added to the thing
How to Create a Map Object
To create a Map
object, you’ll be able to name the Map()
constructor as follows:
The code above creates a brand new empty Map
object.
Map Object Methods and Properties
A Map
object has the next strategies and properties:
set(key, worth)
– Adds a key/worth pair to a Mapget(key)
– Retrieves a price from a Map (returnsundefined
if key does not exist)has(key)
– Checks if a Map has a particular keydelete(key)
– Removes a particular key from a Mapclear()
– Removes all gadgets from a Mapkeys()
– Returns all keys in a Mapvalues()
– Returns all values in a Mapentries()
– Returns all keys and values in a Mapmeasurement
– Returns the variety of gadgets in Map
To insert knowledge into the Map
object, you should utilize the set()
technique:
The code above creates a Map
object with 3 entries as follows:
To retrieve a price from the Map
object, it is advisable to use the get()
technique and cross the important thing as its argument:
To see what number of key/worth pairs a Map
has, you’ll be able to entry the measurement
property:
To see if a sure key exists in a Map
object, you should utilize the has()
technique. See the instance beneath:
To take away a key/worth pair from a Map
object, you should utilize the delete()
technique and cross the important thing of the pair you wish to take away as follows:
If you wish to take away all key/worth pairs, you should utilize the clear()
technique as an alternative:
Other Ways to Create a Map Object
You may also create a Map
object from an Array as follows:
When making a Map
from an Array, it is advisable to create a two-dimensional array and specify two parts in every array.
The first factor would be the key, the second factor would be the worth. Any additional worth within the array can be ignored.
In the instance beneath, the worth ‘Johnson’ from the primary array can be ignored by the Map()
constructor:
Because you’ll be able to create a Map
object from an array, you may also create one from an object. You want to rework the thing into an array first utilizing the Object.entries()
technique.
The following instance exhibits easy methods to use an object to create a Map
:
Iterate Over Map Object Data
To iterate over a Map
object knowledge, you should utilize both the forEach()
technique or the for .. of
loop:
const myMap = new Map([
[1, 'Jack'],
[2, 'Jill'],
['animal', 'Elephant'],
]);
// iterate utilizing the forEach() technique
myMap.forEach((worth, key) => {
console.log(`${key}: ${worth}`);
});
// or utilizing the for .. of loop
for (const [key, value] of myMap) {
console.log(`${key}: ${worth}`);
}
Both strategies give the identical output:
1: Jack
2: Jill
animal: Elephant
When to Use the Map Object
You can consider the Map
object as an upgraded model of the common Object. It can use any kind of knowledge as the important thing worth, whereas an object can solely use string values as keys.
Under the hood, the Map
object performs higher when it is advisable to add and take away keys, so that you may think about using it when your knowledge modifications continuously.
Also, the Map object has many helpful strategies for knowledge manipulation, resembling has()
to see if the Map incorporates a particular key, keys()
to get all keys outlined within the Map
, values
to get all values, and entries()
to get all key/worth pairs.
But in the event you solely wish to create an object with out additional manipulation, then you definitely needn’t use the Map
object.
One instance is once you ship a community request utilizing the fetch()
technique. You would create an object and convert it right into a JSON string, so utilizing a Map
object will not give any profit.
Set Object Explained
The Set
object lets you retailer a group of parts, identical to an Array. The variations between a Set
and an array are:
- A
Set
requires all parts to be distinctive - A
Set
has fewer strategies for knowledge manipulation
How to Create a Set Object
To create a brand new Set
object, it is advisable to name the Set()
constructor as follows:
The code above will create a brand new empty set.
Set Object Methods and Properties
A Set
object has the next strategies and properties:
add(worth)
– Adds a price to a Sethas(worth)
– Checks if a Set incorporates a particular worthdelete(worth)
– Removes a particular worth from a Setclear()
– Removes all gadgets from a Setkeys()
– Returns all values in a Setvalues()
– Returns all values in a Setentries()
– Returns all values in a Set as[value, value]
arraymeasurement
– Returns the variety of gadgets in Set
Note that the keys()
and values()
strategies in a Set object return the identical output.
There’s additionally the entries()
technique which returns an array as follows:
Output:
Notice how the values are repeated as soon as in every array above. The entries()
technique is created to make Set
much like the Map
object, however you most likely do not want it.
There are additional strategies that you should utilize to work together with one other Set
object. We’ll talk about them within the subsequent part.
To add a component to the Set object, you should utilize the add technique:
To get all values saved in a Set
, name the values()
technique:
To test if the Set
has a particular worth, use the has()
technique:
To take away a single worth, name the delete()
technique. To take away all values, use the clear()
technique:
Set Composition Methods
Aside from the common strategies above, Set
additionally has composition strategies that you should utilize to carry out numerous set idea operations resembling distinction, union, and intersection.
The following desk is from MDN Set documentation:
For instance, you will get a set containing the variations between two different units as follows:
Here, the setA.distinction(setB)
returns a Set
containing values distinctive to the setA
object.
The reverse values are returned once you run setB.distinction(setA)
technique.
Note that these strategies are new additions to the JavaScript normal, and as of this writing, solely Safari 17 and Chrome 122 assist these strategies.
Most doubtless, these strategies can be included in Node.js quickly.
Iterate Over a Set Object
To iterate over a Set
object, you should utilize both the forEach()
technique or the for .. of
loop:
const mySet = new Set(['Jack', 'Jill', 'John']);
// iterate utilizing the forEach() technique
mySet.forEach(worth => {
console.log(worth);
});
// or utilizing the for .. of loop
for (const worth of mySet) {
console.log(worth);
}
Output:
Jack
Jill
John
When to Use the Set Object
You can consider the Set
object as the choice model of the common Array.
Because a Set
object ignores duplicate values, you should utilize this object to purge duplicates from an Array, then flip the Set
object again to an Array:
Another cause you could wish to use a Set
is when it is advisable to compose a number of set objects utilizing the composition strategies, resembling union()
and distinction()
. These strategies should not out there in an Array.
Conclusion
In this text, you have realized how the Map and Set objects work and when to make use of them in your code.
If you loved this text and wish to take your JavaScript abilities to the following degree, I like to recommend you take a look at my new guide Beginning Modern JavaScript right here.
The guide is designed to be straightforward for freshmen and accessible to anybody seeking to be taught JavaScript. It offers a step-by-step light information that can make it easier to perceive easy methods to use JavaScript to create a dynamic net utility.
Here’s my promise: You will really really feel such as you perceive what you are doing with JavaScript.
See you later!