Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

An Introduction to Sets in JavaScript

DZone 's Guide to

An Introduction to Sets in JavaScript

Never deal with duplicates in your collections again.

· Web Dev Zone ·
Free Resource

collection-of-old-timey-soda-bottles

Eliminate duplicates in your collection with sets

Sets are a new object type included in ES6 that allow the creation of collections of unique values. The values in a set can be either simple primitives, such as strings and integers or more complex object types like object literals or arrays. Think of sets as an array with no repeated elements.

There are many instances where we have an array containing many elements that we want to convert to a unique array. While it can be done by brute force on the array, checking elements, using loops, distinct callback method, etc., the best method is using  set().

You may also like: Object-Oriented JavaScript.

Syntax:

new Set([iterable]);


Let’s first see an example:

let arrayOne=['1','2','1','2']

console.log(arrayOne)
// ['1','2','1','2']

let setOne= new Set(arrayOne) 

for(elem of setOne){
  console.log(elem)
}
//'1'
//'2'


// Another way of doing
let setTwo= [...new Set(arrayOne)]

console.log(setTwo)
// ["1" ,"2"]


It is clear from the example that by making a new set from an array and using the spread operator, you can make a set into an array.

Set Methods

Now let's look at some basic set methods, you may not need them but it best to be familiar with them in order to optimize your code:

  • add
  • size
  • has
  • forEach
  • delete
  • clear
let fruits = new Set();

fruits.add('apple');
fruits.add('banana');
fruits.add('kiwi');
fruits.add('orange');
console.log(fruits.size); // 4
fruits.add('orange');
console.log(fruits.size); // 4

console.log(fruits.has('apple')); // true
fruits.delete('apple');
console.log(fruits.has('apple')); // false

fruits.forEach(fruit => {
  console.log(`I love eating ${fruit}!`);
});

// 'I love eating banana!'
// 'I love eating kiwi!'
// 'I love eating orange!'

 fruits.clear();
console.log(fruits.size); // 0


It’s pretty much straight forward, the add the method adds elements, the delete method deletes them, the has method has the same functionality as includes in arrays, and the clear method empties the set.

As we saw in the syntax, the set method takes an iterable as an argument, so a string can also be used as an argument.

console.log('I will only contain unique or distinct letter'.length); // 45

let sentence = new Set('I will only contain unique or distinct letter');

console.log( sentence.size); // 17

for(letter of sentence){
  console.log(letter)
}


// 'I'
//  ' '
// 'w'
// 'i'
// 'l'
// 'o'
// 'n'
// 'y'
// 'c'
// 't'
// 'a'
// 'u'
// 'q'
// 'e'
// 'r'
// 'd'
// 's'


Now, let’s look at the practical examples of the set method:

function union(setA, setB) {
    var _union = new Set(setA);
    for (var elem of setB) {
        _union.add(elem);
    }
    return _union;
}

function intersection(setA, setB) {
    var _intersection = new Set();
    for (var elem of setB) {
        if (setA.has(elem)) {
            _intersection.add(elem);
        }
    }
    return _intersection;
}


function difference(setA, setB) {
    var _difference = new Set(setA);
    for (var elem of setB) {
        _difference.delete(elem);
    }
    return _difference;
}

//Examples
var setA = new Set([1, 2, 3, 4]);
var    setB = new Set([2, 3]);
var   setC = new Set([3, 4, 5, 6]);

union(setA, setC); // => Set [1, 2, 3, 4, 5, 6]
intersection(setA, setC); // => Set [3, 4]
difference(setA, setC); // => Set [1, 2]


Conclusion

In the end, I want to conclude that sets should be used when dealing with distinct or unique elements in a dataset. Arrays should be the preferred choice first and foremost as they have enough methods and functions for dealing with almost every question.


Related Articles

Topics:
javascript ,arrays ,tutorial ,coding ,sets ,javascript array ,javascript arrays

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}