DEV Community

Ashutosh Kumar Singh
Ashutosh Kumar Singh

Posted on • Originally published at Medium on

1 1

An Introduction to Sets in JavaScript

Using sets to deal with unique elements in a dataset

Photo by JOSHUA COLEMAN on Unsplash

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 like 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().

Syntax:

new Set([_iterable_]);
Enter fullscreen mode Exit fullscreen mode

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"]
view raw set1.js hosted with ❤ by GitHub

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
view raw set2.js hosted with ❤ by GitHub

It’s pretty much straight forward, the add 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'
view raw set3.js hosted with ❤ by GitHub

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]
view raw set4.js hosted with ❤ by GitHub

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.


SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay