The Set Data Structure in Javascript

Learn about how to use and when to use Set in JavaScript.


The Set object allows you to create a collection of unique values(each value can occur only once).

Set can contain any type of value (primitives or object reference).

Set stores elements in the insertion order.

The Set doesn’t contain’s keys πŸ”‘ like a Map object.

The uniqueness of elements of the Set are checked using the SameValueZero algorithm. This algorithm is similar to === (strict equal) except in one case where NaN === NaN evaluates to true, so that multiple NaN is not inserted in the Set.

Creating aΒ Set

Syntax: new Set([iterable]) β†’ returns a Set object.

var set1 = new Set([1, 2, 1, 3, 4, 5]);
set1; // Set(5) {1, 2, 3, 4, 5} ; duplicate values are removed.
Creating an empty set
var set2 = new Set();

Properties

size β†’ Returns the number of elements in the Set

var number = new Set([1,2,3,4,5])
number.size ; 

Methods

add()

The add() method appends the element passed to the end of a Set object and returns the Set object.

var fruits = new Set(['πŸ‡', 'πŸ‰', '🍊', '🍈' ]);
fruits.add('πŸ‹');
fruits; // Set(5) {'πŸ‡', 'πŸ‰', '🍊', '🍈', 'πŸ‹'};

When we try to add duplicate values it is not inserted.

fruits.add('🍊'); // already present in the set
fruits; // Set(5) {'πŸ‡', 'πŸ‰', '🍊', '🍈', 'πŸ‹'};

The add method is chain-able

fruits
.add('🍌')
.add('πŸ“')
.add('🍎');
fruits; // Set(8) {"πŸ‡", "πŸ‰", "🍊", "🍈", "πŸ‹", …}

Adding objects to Set

var set = new Set();
set.add({i : 10});
set.add({i : 10});
set; //Set(2) {{…}, {…}}
// Even-though objects look same, each object has different reference, so they are not ===
//
An object reference means that it compares the memory address of the object and not the actual key/value pairs contained in the object.
--------------------------------------------------------------------
var obj = {i :100};
set.add(obj);
set.add(obj);
// Now the obj points to same object reference so it is not inserted
--------------------------------------------------------------------
obj.i =1000;
// the value in the set is changed because we are storing the address.

has()

The has() method returns true if an element with the specified value exists in a Set object, and false if the value is not present in the SetΒ .

Syntax: has(valueToBeChecked) β†’ returns either true or false.

var fruits = new Set(['πŸ‡', 'πŸ‰', '🍊', '🍈' ]);
fruits.has('πŸ‡'); //true
fruits.has('🍌'); //false

has method with object

var set = new Set();
var obj = {i :100};
set.add(obj);
set.has(obj); // true
set.has({i : 100}); //false, because they are different object  reference.

values()

The values() method returns a new Iterator object that contains the values for each element in the Set object in insertion order.

var fruits = new Set(['πŸ‡', 'πŸ‰', '🍊', '🍈' ]);
fruits.values();  // SetIterator {"πŸ‡", "πŸ‰", "🍊", "🍈", "πŸ‹", …}
--------------------------------------------------------------------
//use destructor to print only the values
console.log(...fruits.values())
or 
var fruitsArray = ([...fruits.values]);

entries()

The entries() method returns a new Iterator object that contains an array of [value, value] in insertion order.

There is no key in a Set so it returns in the format of [value, value]Β .

var fruits = new Set(['πŸ‡', 'πŸ‰']);
fruits.entries();  SetIterator {"πŸ‡" => "πŸ‡", "πŸ‰" => "πŸ‰"}
--------------------------------------------------------------------
// you can use for...of 
for(var [key ,value] of fruits.entries()) {
console.log(key, value);
}

delete()

The delete() method removes the specified element from a Set object.

SyntaxΒ : delete(valueToBeDeleted)

Returns true if an element in the Set is deleted, otherwise it returns false.

var fruits = new Set(['πŸ‡', 'πŸ‰']);
fruits.delete('πŸ‡'); //true
fruits; //Set(1) {"πŸ‰"}
fruits.delete('🍌'); false.

clear()

The clear()method empties theSet object.

var fruits = new Set(['πŸ‡', 'πŸ‰']);
fruits.size; // 2
fruits.clear(); 
fruits.size; // 0

Using forEach on a Set object:

let print= function(key , value, set) {
   console.log(value);
}
var fruits = new Set(['πŸ‡', 'πŸ‰']);
fruits.forEach(print)
//output
πŸ‡
πŸ‰

Tips andΒ Tricks

  1. When we pass a string as an argument when creating a Set, then it creates a set with all characters as separate elements.
var text = 'LEARN';
var mySet = new Set(text);  
//Set(5) {"L", "E", "A", "R", "N"}

2. Removing duplicate elements from an array

var names= [ 'John', 'Brandi', 'Tony', 'John'];
var uniqueNames = [...new Set(names)]
uniqueNames = [ 'John', 'Brandi', 'Tony'];

3. How array and set are different

  • Set objects store unique values, whereas array can have duplicate values
  • In an array, we need to use the indexOf method to check the availability of element in the array, but in a set we can use the has method, which is compared to be faster than indexOf method.


  • The value NaN cannot be found with indexOf in an array.
  • Set objects let you delete elements by their value. With an array, you would have to splice based on an element’s index.

You can read about map πŸ—Ί in details here.

If you find this helpful surprise 🎁 me here.

Share if you feel happy πŸ˜ƒ πŸ˜† πŸ™‚Β .

Follow Javascript JeepπŸš™ if you feel worthy.


https://gitconnected.com/learn/javascript

Leave a comment

Design a site like this with WordPress.com
Get started