JavaScript Sets

When learning about JavaScript, you may be interested in the Sets object to process data. Sets are commonly used in ES6 because of its simplicity in operation and fast processing speed. Learn more about JavaScript Sets in this article.

What is JS Sets

Set is a set of values that cannot be duplicated, that is, in a set no two identical values can occur. The data types contained in Set are very diverse such as strings, numbers… or with complex data structures such as arrays or objects.

Methods in JS Set

MethodsDescription
new Set(iterable)creates a set from an iterable object, usually an array of elements
set.add(value) add element and return itself (Set).
set.delete(value)delete the element. Returns true if the element exists, false otherwise.
set.has(value) check the element exists in the Set, return true/false.
set.clear()deletes all elements in the Set.
set.size the number of elements in Set
set.values()Returns an iterator with all values in a Set

Initialize Set in JS

Initializing Set is the first thing you need to do if you want to use Set. The syntax to initialize Set in Javascript is:

new Set([iterable]);

  • The iterable parameter is optional. If you don’t pass arguments to the constructor, Set will be empty, meaning there are no elements in the Set.
  • Conversely, if you pass an iterable object, all the elements of the object will be added to the Set.

For example:

// Create a Set
let fruits = new Set(["mango", "apple", "watermelon", "banana"]);
 console.log(set);
 // Set(4) {"mango", "apple", "watermelon", "banana"}

In case your values are duplicated, you can get rid of them using Set to get the unique value. For example:

const color1 = ["red", "blue", "black", "red", "yellow"]
const color2 = [...new Set(color1)]
console.log(b)  // [ "red", "blue", "black", "yellow" ]

add() Method

To add an element to a Set in JavaScript, you can use the add() method as follows:

set.add(value);

  • If the Set has no value element, the set.add(value) method will add the value to the Set and return the Set itself.
  • If value already exists, the set.add(value) method will ignore and return the Set itself.

To understand better, see the following code:

// Create a Set
let fruits = new Set(["mango", "apple", "watermelon", "banana"]);
// Add 2 Values to the Set
fruits.add("cherry");
fruits.add(30);

set.size Method

The set.size() method allows you to get the number of elements of a Set in JavaScript. Take a look in the following example:

const color1 = new Set([ "red", "blue", "black", "red"]);
console.log(color1.size);
// 3 - because the set has only three elements ["red", "blue", "black"]

Accessing the elements of Set

You can access the elements of a Set object using the values() method and check if there are any elements inside the Set object using the has() method.

For example:

// Create a Set
const fruits = new Set(["mango", "apple", "watermelon", "banana"]);
// List all Elements
let text = "";
for (const x of fruits.values()) {
   text += x;
}

Output:

Iterating Set values:

mango
apple
watermelon
banana

We can use the has() method to check if the element exists in the Set object.

const fruits = new Set(["mango", "apple", "watermelon", "banana"]);
console.log(set1.has(mango)); // false
console.log(set1.has("mango")); // true

Remove elements of data type Set

You can use the clear() and delete() methods to remove elements from an object of type Set.

The delete() method is responsible for removing a specified element from a Set object. The clear() method will be responsible for removing all elements from a Set object.

For example:

const fruits = new Set(["mango", "apple", "watermelon", "banana"]);
console.log(fruits); // Set(4) {"mango", "apple", "watermelon", "banana"}
// remove an element
fruits.delete("mango");
console.log(fruits); // Set(3) {"apple", "watermelon", "banana"}
fruits.delete("apple");
console.log(fruits); // Set(2) { "watermelon", "banana"}
// remove all element
fruits.clear();
console.log(fruits); // Set(0) {}

forEach() method

You can iterate through the elements of a Set object using a for loop or the forEach() method. The elements will be traversed in order when adding elements is performed.

For example:

// Create a Set
const fruits = new Set(["mango", "apple", "watermelon", "banana"]);
// List all of elements
let text = "";
fruits.forEach (function(value) {
   text += value;
})

Output:

forEach() calls a function for each element:

mango
apple
watermelon
banana

Using for…of

Alternatively you can also use for…of to iterate over the elements:

const fruits = new Set(["mango", "apple", "watermelon", ]);
for (const x of fruits) {
   console.log(x);
}
/*
  *mango
  * apple
  * watermelon
  */

Convert Set to Array

You can use the forEach method of Set in JavaScript, similar to Array. But what about other methods like: map, filter,…?

In fact, Set does not support these methods.

But you can completely convert Set to Array to use Array’s methods. Then you convert the Array back to a Set.

To convert Set to Array, you can use Array.from or use spread operator, for example:

// Create a Set
const fruits = new Set(["mango", "apple", "watermelon", "banana"]);
// convert set to array using Array.from
const myArray1 = Array.from(fruits);
console.log(myArray1);
// ["mango", "apple", "watermelon", "banana"]

// convert set to array using spread (...)
const myArray2 = [...fruits];
console.log(myArray2);
// ["mango", "apple", "watermelon", "banana"]

Suppose, you use the filter method to remove the element “mango”:

const myArray3 = myArray1.filter(function(value){
     if (value == "mango"){
         return false;
     }
     return true;
});

console.log(myArray3);
// ["apple", "watermelon", "banana"]

Now, you convert the Array back to a Set – using the Set initializer method:

const fruits2 = new Set(myArray3);
console.log(fruits2);
// Set(3) {"apple", "watermelon", "banana"}

JS Sets Tutorials

Summary

To summarize, through the article “Javascript Sets” we have provided you with more knowledge about Sets in JS. This is a commonly used object when working with JS. To learn more about JavaScript and other programming languages you can visit LearnShareIT.com. Thank you for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *