Beginners Guide to Set and Map in JavaScript

Beginners Guide to Set and Map in JavaScript

Hello world, Akwaaba ๐Ÿ‘‹. In recent past, JavaScript relied heavily on Arrays and Object as the only data structure. Whilst Arrays were being used to store ordered collections,Object played its role of storing keyed collections. With the introduction of ES6, two more data structures have been added, these are the : Set and Map. By the end of this post, you should be proficient in using Set and Map as data structures. This post will be dedicated to learning and grasping the concept of Set, we will focus on Map in our next post.

If you are ready, let's take a dive ๐ŸŒŠ into the world of Set

What is Set ?

A Set is a special type of collection, that allows you to store unique values of any data type.

It is a "set of values" (without keys), where each value may occur only once. .

Why Set is important

Because Set helps you store unique values of any type, whether primitives or objects reference; it helps develops to remove duplicated or repeated values from any data so we can keep only the unique values

Set Methods

Set has some methods we can use to make it efficient, let's take a look at these.

  • new Set(iterable)

  • set.add(value)

  • set.delete(value)

  • set.has(value)

  • set.clear()

  • set.size

Creating a Set

new Set(Iterable)

The above method helps create the Set. Becuase Set is to keep unique values; if an array or any iterable object is provided to it, it copies the unique values from it into the set.

Let's see an example

Example creating a new set from an array

Let's take a scenario were you have an array of all ordered menus and your task is to create a unique set of menus from the array. In order words, you want each menu to appear only once so you want to remove any duplicated menu from the array.

The code below demonstrate how to create a Set of ordered menu


/* Pass the array of menus  into the the parenthesis */
const orderedMenu = new Set(["Macroni","Pizza","Rice", "Pizza","Chicken wings", "Chicken wings","Rice"])

console.log(orderedMenu)
/* Set(4) {"Macroni", "Pizza", "Rice", "Chicken wings"} */
/* Each menu appears only once. All duplicated items have been removed creating a set of unique values */

How the code above works

As was defined, the Set is a collection of unique values meaning when we create a Set and we supply it with an array of elements, it will remove any duplicate elements or items from the array and pass the unique values to a declared variable.

Let's see what is happening with the code above.

  • In the above, Pizza, Rice and Chicken wings have been repeated in the array of items, so the Set will only keep one of the items.

  • It will keep one Pizza, Rice and Chicken wings and ignore any duplicate.

  • Even though we initially had 7 items in the array, the Set will remove the duplicated items keep only 4 items or values out of the 7.

Creating another Set

To solidify the concept of Set, let's create a new Set from an array of alphabets.

const chars = new Set(['a','b','c','a','b','b','d']);
console.log(chars)
/* All duplicates are gone * /
/* Set(4) {"a", "b", "c", "d"} */

A cool trick, you can convert the Set to an Array using the Array.from() method. As an icing on the cake, lets convert our result back to an array

console.log(Array.from(chars));
/* ["a", "b", "c", "d"] */

Getting the size of a set

To find out the number of elements the set holds, you can use the size property. To do that, use the syntax below :

mySet.size  /* count the number of elements in a set*/

Now, let's take our initial chars set and count the number of elements in the set

console.log(chars.size);
/* 4 */

Adding elements to a set

You can also add elements to a set using the mySet.add(value) method.
This method adds an element to a set and returns the set itself.

Example adding more menus to the ordered menu array

Let's revisit the ordered menu array we created above ๐Ÿ‘† and this time, lets assume some more orders have been placed so we need to add it to the set.

Let's see how to achieve that

/* Add Fries to the ordered Menu */
console.log(orderedMenu.add("Fries")); 
/*{"Marcroni", "Pizza", "Rice", "Chicken wings", "Fries"} */

In the above, we added Fries to the orderedMenu Set, now the number of items in the set will change to 5 since Fries has been added to it.

But what if you want to add multiple items, do we need to be calling the mySet.add() method each time ? ๐Ÿ˜Ÿ. That will definitely be a lot of works, if we have let's say 5 more menus to add. To address this issue, you use a chain statement to add the multiple items.

Now, let's add three menus to our orderedMenu set.

Let's take a look at the code below:

console.log(orderedMenu.add("Fries").add("Spaghetti").add("Banku);
/* Set(7) {"Macroni", "Pizza", "Rice", "Chicken wings", "Fries", "Spaghetti", "Banku"} */

In the above, we have added three more items (Fries, Spaghetti and Banku ) to the orderedMenu set. If we need to verify the number of items in the Set we can simply run orderedMenu.size and we will get the number 7 returned. Clear right ! ๐Ÿ˜‚

Using Repeated calls of add method

Repeated calls of the add() method with the same value do not do anything. This feature allows values to appear only once in the set

Let's assume you have visitors coming to your website and you want the visitors to be counted only once. Meaning if the same visitor visits the website multiple times, you only want to count him once. Let's see how to achieve that

let visits = new Set(); /* creates the set */
/* the  define the visitors object */
let john = {name:"John", location: "Accra"};
let emma = {name:"Emmanuel", location: "Lagos"};
let ama = {name: "Ama", location: "Tema"};

/* user visits websites so you add to the set */
visits.add(john);
visits.add(emma);
visits.add(ama);

console.log(visits);
/*Set(3) {{โ€ฆ}, {โ€ฆ}, {โ€ฆ}} */

Now, let's assume john and emma revisits the site, so we want to add them again to the visits Set.

/*john and emma revisits the site so they are being added to the visits set */
visits.add(john);
visits.add(emma);
console.log(`the visits will still  be `, visits);
/* the visits will be  Set(3) {{โ€ฆ}, {โ€ฆ}, {โ€ฆ}} */ ๐Ÿ˜ฎ

What is happening in the above what happened to the revisits of john and emma. They were not added to the set. Why ? ๐Ÿ˜

  • The size of the visits set is still 3, check it out using visits.size method.

  • john and emma objects were not added to the set. You should know that Set only hold unique items hence visits set should only hold unique values since john and emma have already visited the website, they will be duplicated but Set don't entertain duplicates so it removes the duplicated values and only store unique values ๐Ÿ˜Ž

Checking if a value is in a set

You can use the has() method to check if a value is in a given set. The has() method will return true if the Set contains the element, otherwise, it returns false.

Ok, now lets check if our visits Set has the john object

console.log(visits.has(john))
/* true */ ๐Ÿ˜€

Removing an element from a set

The delete(value) method removes a specified element from a Set. It returns true if the value existed at the moment of the call otherwise false.

Let's revisit the visits Set and remove the emma object from the set

console.log(visits.delete(emma));

Looping the elements of a set

You can loop over a Set using either the for...of or the forEach.

Let's create a set of fruits and iterate over the items

let fruits  = new Set(["Banana","Orange","Apples","Mango"]);
console.log(fruits);
/*iterate over each item in the Set */

for(const fruit of fruits){
    console.log(fruit)
}

/*Banana Orange Apples Mango*/

When you iterate over an element, the order of the element is the same as the insertion order.

Removing duplicates from an array

The big takeaway from Set is to help remove duplicates from an array or any iterable.

Let's assume we have an array of roles of staff and we want to store only the unique roles in an array. Let's see how we can achieve that using Set

let staffRoles = ["Accountant", "Manager", "Developer", "Receptionist", "Accountant", "Developer"]
/* create the Set */
let uniqueStaff = new Set(staffRoles);
console.log(uniqueStaff); /* Set(4) {"Accountant", "Manager", "Developer", "Receptionist"} */
/* convert to array */
let newStaffRoles = [...uniqueStaff]; /*spread operator helps expand the sets elements into an array */
console.log(newStaffRoles);
/*(4) ["Accountant", "Manager", "Developer", "Receptionist"] */

Another example of getting unique values

Let's take a scenario where you want to remove duplicated cities or in other words, get only the unique cities from an array of objects.

For instance, we have an array of objects that contains distances from one city in Nigeria to the other city and we only want to get a collection of the unique cities (list of all the cities) so we can work with it later.

Let's see how we can achieve that using Set.

/* array of objects specifying distance from one city to the other */
const  cityDistances = [
  { from: "Lagos", to: "Kano", distance: 65 },
  { from: "Ibadan", to: "Kano", distance: 151 },
  { from: "Port Harcourt", to: "Jos", distance: 16 },
  { from: "Jos", to: "Lagos", distance: 68 },
  { from: "Abuja", to: "Kaduna", distance: 24 },
  { from: "Kaduna", to: "Jos", distance: 76 },
  { from: "Benin", to: "Enugu", distance: 51 }
];

let  uniqueCities = new Set(); /*Creates an empty  set  */
/*iterate through each city and add it to the empty set */
cityDistances.forEach(distance =>{
    uniqueCities.add(distance.from);  /* use mySets.add()  method to add each value to the set*/
    uniqueCities.add(distance.to)
})
console.log(uniqueCities);
/*Set(9) {"Lagos", "Kano", "Ibadan", "Port Harcourt", "Jos", โ€ฆ} */
/* convert the Set into an array */
console.log(Array.from(uniqueCities));
/* (9) ["Lagos", "Kano", "Ibadan", "Port Harcourt", "Jos", "Abuja", "Kaduna", "Benin", "Enugu"] */

Sweet right ๐Ÿ˜†. Ok, let's conclude the post on Set with a summary.

Summary

In summary, Set is not a replacement of arrays, it however helps as store a collection of unique values so anytime you want to store some unique values or remove duplicated items from an array or any iterable, you should use Set.

If you found value in this post, kindly share on your social media channels. It will be a great reference to a code newbie. Did you find value in my post, i would love to read you comment on it.

In my next post, we will take a look at the Map. Me daa se

PS: Akwaaba and Me daa se are Ghanaian ๐Ÿ‡ฌ๐Ÿ‡ญ dialect meaning, Welcome and Thank you respectively

Writing with โค๏ธ from ๐Ÿ‡ฌ๐Ÿ‡ญ