Home » How to Use the JavaScript Map and Set Objects – Explained with Code Examples

How to Use the JavaScript Map and Set Objects – Explained with Code Examples

by Icecream
0 comment

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:

const myMap = new Map();
Create a Map object in JavaScript

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 Map
  • get(key) – Retrieves a price from a Map (returns undefined if key does not exist)
  • has(key) – Checks if a Map has a particular key
  • delete(key) – Removes a particular key from a Map
  • clear() – Removes all gadgets from a Map
  • keys() – Returns all keys in a Map
  • values() – Returns all values in a Map
  • entries() – Returns all keys and values in a Map
  • measurement – Returns the variety of gadgets in Map

To insert knowledge into the Map object, you should utilize the set() technique:

const myMap = new Map();

myMap.set(1, 'Jack');
myMap.set(2, 'Jill');
myMap.set('animal', 'Elephant');
Inserting values to the Map object

The code above creates a Map object with 3 entries as follows:

Map(3)
0: {1 => "Jack"}
1: {2 => "Jill"}
2: {"animal" => "Elephant"}
The Map object entries

To retrieve a price from the Map object, it is advisable to use the get() technique and cross the important thing as its argument:

console.log(myMap.get(1)); // Jack

console.log(myMap.get('animal')); // Elephant

Retrieving Map object values

To see what number of key/worth pairs a Map has, you’ll be able to entry the measurement property:

myMap.measurement; // 3
Accessing the Map.measurement property

To see if a sure key exists in a Map object, you should utilize the has() technique. See the instance beneath:

myMap.has(1); // true

myMap.has(10); // false
Using the Map.has() technique

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:

myMap.delete(1);

console.log(myMap);
// 0: {2 => "Jill"}
// 1: {"animal" => "Elephant"}
Deleting an entry from the Map object

If you wish to take away all key/worth pairs, you should utilize the clear() technique as an alternative:

myMap.clear();

console.log(myMap); // Map(0) {measurement: 0}
Clearing a Map object

Other Ways to Create a Map Object

You may also create a Map object from an Array as follows:

const myMap = new Map([
  [1, 'Jack'],
  [2, 'Jill'],
  ['animal', 'Elephant'],
]);
Creating a Map from an Array

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:

const myMap = new Map([
  [1, 'Jack', 'Johnson'], // the worth 'Johnson' is ignored
  [2, 'Jill'],
  ['animal', 'Elephant'],
]);
Creating a Map from an array with greater than two values 

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:

const particular person = {
    'identify': 'Jack',
    'age': 20,
}

const myMap = new Map(Object.entries(particular person));

console.log(myMap); // Map(2) { 'identify' => 'Jack', 'age' => 20 }
Creating a Map from an object

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:

const mySet = new Set();
Creating a brand new Set object

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 Set
  • has(worth) – Checks if a Set incorporates a particular worth
  • delete(worth) – Removes a particular worth from a Set
  • clear() – Removes all gadgets from a Set
  • keys() – Returns all values in a Set
  • values() – Returns all values in a Set
  • entries() – Returns all values in a Set as [value, value] array
  • measurement – 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:

const mySet = new Set(['Jack', 'Jill', 'John']);

console.log(mySet.entries());
Running Set entries() technique

Output:

[Set Entries] {
  [ 'Jack', 'Jack' ],
  [ 'Jill', 'Jill' ],
  [ 'John', 'John' ]
}
Output of Set entries() technique

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:

const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(3);

console.log(mySet); // [1, 2, 3]
Adding new parts to the Set object

To get all values saved in a Set, name the values() technique:

mySet.values(); // [Set Iterator] { 'Jack', 'Jill', 'John' }
Getting all values from a Set object

To test if the Set has a particular worth, use the has() technique:

mySet.has('Jack'); // true

mySet.has('Michael'); // false
Check if a Set has a particular worth

To take away a single worth, name the delete() technique. To take away all values, use the clear() technique:

mySet.delete('Jill');

mySet.clear();
Delete a single worth or clear all from Set

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:

set-composition-methods
A List of Set Composition Methods

For instance, you will get a set containing the variations between two different units as follows:

const setA = new Set([1, 2, 3, 4, 5]);

const setB = new Set([4, 5, 6, 7, 8]);

const diffsA = setA.distinction(setB); // Set(3) {1, 2, 3}
const diffsB = setB.distinction(setA); // Set(3) {6, 7, 8}
Example of utilizing the Set distinction() technique

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:

const myArray = [1, 1, 2, 2, 3, 3];

const distinctiveArray = [...new Set(myArray)];

console.log(distinctiveArray); // [ 1, 2, 3 ]
Creating a novel array with the assistance of Set

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.

beginning-js-cover

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!

You may also like

Leave a Comment