The Ultimate Guide To Set and Map in JavaScript

The Ultimate Guide To Set and Map in JavaScript

Hey there, JavaScript Developers👩‍💻

In this article we'll dig deeper into the concepts of Set and Map.

What is a Set?

A Set is a collection of unique values. That means the set can never have any duplicates and can hold any values of any data type. You can iterate through the elements of a set in insertion order.

Okay, this sounds interesting. So the question is how to create a set?

  • To create a set we write- new Set() and in the parentheses, we need to pass an iterable.

const ordersSet= new Set(['Pasta','Pizza','Coffee','Pasta','Pizza']);

console.log(ordersSet);  // {'Pasta', 'Pizza', 'Coffee'}

Here in the above example, we see some duplicate set elements like Pasta and Pizza. When we log in to the console we get a set that has a size of 3.

You might think the elements were 5 before then how come it be 3 now? 🧐

This is when sets come into play. It removes the duplicates like they never existed and we get to see a collection of unique values.

Set has several methods. Let's have a look at them.

  • set.has(value)

The method returns true if the value exists in the set, otherwise false.

const ordersSet= new Set(['Pasta','Pizza','Coffee','Pasta','Pizza']);

console.log(ordersSet.has('Bread'));  //false
  • set.add(value)

The method not just adds a value but even returns the set itself.

const ordersSet= new Set(['Pasta','Pizza','Coffee','Pasta','Pizza']);

console.log(ordersSet);  // {'Pasta', 'Pizza', 'Coffee'}
console.log(ordersSet.add('Garlic Bread'));
  • set.delete(value)

The method removes the value, returns true if the value existed at the moment of the call, otherwise false.

const ordersSet= new Set(['Pasta','Pizza','Coffee','Pasta','Pizza']);

console.log(ordersSet);  // {'Pasta', 'Pizza', 'Coffee'}
console.log(ordersSet.delete('Pizza'));
  • set.clear()

This method deletes all of the elements of a set.

const ordersSet= new Set(['Pasta','Pizza','Coffee','Pasta','Pizza']);

console.log(ordersSet.clear()); // {}
  • set.size

This method returns the element count.

const ordersSet= new Set(['Pasta','Pizza','Coffee','Pasta','Pizza']);

console.log(ordersSet);  // {'Pasta', 'Pizza', 'Coffee'}
console.log(ordersSet.size); //3

You might think about how to retrieve value out of a set?

Let me tell you that in a set there are no indexes. In fact, there is no way of getting values out from a set. And if we see logically this makes sense.

  • Sets are also iterable. So we can loop over them.
for(const order of ordersSet)
console.log(order);

The Set object is quite useful as it lets you store unique values of any type, whether primitive values or object references.

The main use-case of sets is actually to remove duplicate values from an array like this👇

const staff= ['Waiter','Chef','Waiter','Manager','Chef','Waiter'];

const staffUnique= new Set(staff);
console.log(staffUnique); // { 'Waiter','Chef','Manager'}
  • Conversion from a Set to an Array is quite simple because they're both iterable.
const staffUnique=[...new Set(staff)];
console.log(staffUnique);

Map

What is a Map?

A Map is a data structure that we can use to map values to keys just like an object. Any value (both objects and primitive values) may be used as either a key or a value.

The map() method calls the provided function once for each element in an array, in order.

const rest= new Map();
rest.set('name','Classico Italiano');

Overview- To fill up the map() we can use the set method. We see that the set method is pretty similar to the add method. Remember we can use any data type that we want.

Let's understand this with an example- For instance, the restaurant has two locations.

rest.set(1,'Firenze,Italy');
rest.set(2,'Lisbon,Portugal');

console.log(rest.set(2,'Lisbon,Portugal'));

And calling the set method like this doesn't only update the map that is called on but it also returns the map. We can use this way to even chain set methods.

Methods and properties are as follows:

  • map.get(key)

To read the data from the map we use the get method.

console.log(rest.get('name'));
  • map.has(key)

We use this method to check if a map contains a certain key or not. Returns true if the key exists, false otherwise.

console.log(rest.has('categories')); //false
  • map.delete(key)

This method removes the value by the key.

console.log(rest.delete(2));
  • map.clear()

This method removes everything from the map.

rest.clear();
console.log(rest); //{}
  • map.size

It returns the current element count.

console.log(rest.size);

⚡Do you know we can even use objects and arrays as a Map key?

Let me demonstrate this to you with an example- Here we use an array.

const arr=[1,2];
rest.set(arr,'Test');

console.log(rest);
console.log(rest.size);
console.log(rest.get(arr)); //Test

⚡Using objects as keys is one of the most notable and important Map features. The same does not count for Object.

let john = { name: "John" };

// for every user, let's store their visits count
let visitsCountMap = new Map();

// john is the key for the map
visitsCountMap.set(john, 123);

alert( visitsCountMap.get(john) ); // 123

For looping over a map, there are 3 methods:

map.keys() – returns an iterable for keys, map.values() – returns an iterable for values, map.entries() – returns an iterable for entries [key, value], it’s used by default in for..of.

⚡You might think what if we want to convert an Object into a Map?

Let me tell you Objects are not iterable. So to convert it we use the object.entries() like this👇

console.log(object.entries(openingHours));

A Map doesn't contain any keys by default. It only contains what is explicitly put into it.

Don't confuse a map as an object as they're quite similar but still a lot different.

Wrapping Up!

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

I know this was a quite long article.😅 Hope you learned something valuable. If you got any questions feel free to ping me on Twitter

Did you find this article valuable?

Support Insha's Blog by becoming a sponsor. Any amount is appreciated!