Javascript – Sets

Sets

Sets are collections of unique values, which can be used to eliminate duplicate elements from an array, which also includes NaN and undefined.

const uniqueNumbers = new Set([1, 2, 2, 3, 3, 4, 5]);
console.log('uniqueNumbers', uniqueNumbers) // [1,2,3,4,5]
JavaScript

With ES5

Befores sets introduction in ES6, there was workaround which developers used to have to create sets but there was limitations to that workaround. Let us see that first to exactly know why there was need for it.

var set = {};
if (!set.foo) {
	set.foo = true;
}
JavaScript

We have created an empty object and assigned true to the properties so that we can check if that value is present.

This works well in the simple scenarios but when we have to use more complex situations we run into the limitations of the object properties.

var set = {};
var key = {};

set[25] = 'sujay';
set[key] = 5;

console.log(set['25']); // sujay
console.log(set[key]); // 5
JavaScript

Here the object internally converts the numeric 25 and key to string ’25’ because object parameters must be string, Thus we cannot use both of them simultaneously.

With ES6

With introduction of Set and WeakSet in ES6, we don’t have to worry about the workaround limitations.

Syntax:

let set = new Set([iterable]);
JavaScript

If an Iterable object like Array is passed then all of its items will be added to the set.

let set = new Set();
set.add(25);
set.add("25");

let set2 = new Set([1,2,3,4,5,6,7,8]);
let set3 = new Set('Sujay');

console.log(set.size); // 2
console.log(set2.size); // 8
console.log(set3.size); // 7 ['S', 'u', 'j', 'a', 'y']
JavaScript

Sets do not convert the values while checking (Except for +0 and 0)

let set = new Set();
let key = {};
let key2 = {};

set.add(key);
set.add(key2);

console.log(set.size); // 2
JavaScript

Sets Methods :

Adding item to the set :

Sets can contain any data type – so you can add objects, numbers, strings or anything else. If you try to add the same value twice, it will appear in the set once:

  1. add(item) – Adds an item or items or values to the set
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(4); // ignores the duplicate values
set.add('4'); 
set.add('My name is Sujay Kundu');
set.add(undefined);
set.add({ a: 0, b: 1});
set.add(null);

console.log(set.size); // 9
JavaScript

Remove item from the set

2. delete(item) – Remove particular items from the set

console.log(set.size); // 9
set.delete(null); // Remove null
console.log(set.size); // 8
JavaScript

Deleting objects from a Set:

Interestingly, objects are still created with seperate references, so you can’t delete an object from a set using the Set.delete() method. Trying to do so still results in the object item appearing in the set:

let mySet = new Set();
mySet.add({o: 4});
mySet.delete({o: 4});

console.log(mySet); // Set(1) {{o: 4}}
JavaScript

Instead, if you want to delete an object from a Set, you have to loop through the set using forEach or something similar. After finding the element you want to delete, simply delete it as normal:

let mySet = new Set();
mySet.add({o: 4});
mySet.forEach((x) => {
	if(x.o == 4) { 
		mySet.delete(x);
	}
});
console.log(mySet); // Set(0) {}
JavaScript


3. clear() – Removes all the items

set.clear(); // Remove all items
console.log(set.size); // 0
JavaScript

Set keys and entries

keys() – Returns an iterable set of keys from that set:

let mySet = new Set();

mySet.add(5);
mySet.add(10);

console.log(mySet.keys()); // SetIterator {5, 10}
JavaScript

entries() – Returns an iterator object that contains an array of items in the way they were added.

Set.entries() is quite strange, since as I sort of mentioned, sets don’t really have keys. In Javascript, typically an entries() method returns the key value pairs from a data structure in an array format, like [key, value]. Since sets don’t have keys, Set.entries() just returns the same value for both key and value. The main reason this method exists is to provide consistency with the Map data type.

let mySet = new Set();

mySet.add(5);
mySet.add(10);
let setEntries = mySet.entries();

for (let x of setEntries) {
	console.log(x);
	// Returns [5, 5], [10, 10]
}
JavaScript

Checking Set Membership

has(item) – Returns true if item is present in the set, false otherwise

The main use case for sets in Javascript is checking membership. This is slightly faster than using something like Array.includes(). To check set membership, you can use the Set.has() method. It returns true, if the set contains the item, and false if it does not:

let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
console.log(mySet.has(10)); // true
JavaScript

Again, this will not work with objects exactly, since an object has a different reference when checked using has. As such, to check if an object is within a set, you must loop through it and check some value within the object:

let mySet = new Set();
mySet.add({o: 4});
mySet.forEach((x) => {
	if(x.o == 4) {
		// the object is in the set
		console.log(`the object ${x.o} is in the set`)
	}
});
JavaScript

Checking the size of a set

while arrays have .length, sets have .size. To check the size or length of a set.

let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
console.log(mySet.size); // 3
JavaScript

Iterating over a Set

Sets themselves are able to be looped through with a simple for loop:

let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
for(let x of mySet) {
    console.log(x); // Returns 5, 10, 20
}
JavaScript

However, sets also come with the forEach() method attached, so you can use that too. Typically for loops are faster, though:

let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
mySet.forEach(() => {
    console.log(x); // Returns 5, 10, 20
}
JavaScript

As well as this, sets come with an iterator method attached too. You can access it like shown in the code below, and then use next() to iterate through each item in a set.

You may not have seen this notation before, but many data structures and prototypes contain an iterator method. Here, we access it via mySet[Symbol.iterator]()

let mySet = new Set();
mySet.add(5);
mySet.add(10);

let setIterator = mySet[Symbol.iterator]();

console.log(setIterator.next()); // Returns { value: 5, done: false }
console.log(setIterator.next()); // Returns { value: 10, done: true }
JavaScript

Simple Iteration with Set

let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
// foreach loop
set.forEach((e) => { console.log(e); });

// 1
// 2
// 3
// 4

// for of loop
for (let item of set) {
    console.log(item);
}

// 1
// 2
// 3
// 4
JavaScript

Iterating objects of Set

let set = new Set();
set.add(1);
set.add('sujay');
set.add({a: 1, b: 2, c: 3, d: 4});

for (let item of set.keys()) {
    console.log(item);
}
// 1
// sujay
// {a: 1, b: 2, c: 3, d: 4}

for (let[key, value] of set.entries()) {
    console.log(key, value);
}
// 1 1 
// sujay sujay
// {a: 1, b: 2, c: 3, d: 4} {a: 1, b: 2, c: 3, d: 4}
JavaScript
let set = new Set();
set.add(1);
set.add('sujay');
set.add({a: 1, b: 2, c: 3, d: 4});

// using `.next()`
const iterator = set.values();

console.log(iterator.next().value);
// 1

console.log(iterator.next().value);
// sujay

console.log(iterator.next().value);
// {a: 1, b: 2, c: 3, d: 4}
JavaScript

1 Comment

Leave a Reply

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