DEV Community

Cover image for JavaScript Sets
Abdelrahman Mohamed
Abdelrahman Mohamed

Posted on

JavaScript Sets

Set is one of the new Data Structures that got added to JS with ES6.

  • Sets are not ordered like array but iterable
  • Sets can only have unique values even if we added duplicate values
//we can create sets like this
const mySet = new Set([1, 2, 2, 5, 5]);
const mySet2 = new Set(['pizza','pasta', 'fries','burger','pizza', 'cheese']);
const mySet3 = new Set('abdelrahman');
console.log(mySet,mySet2,mySet3);
//Set(3) {1, 2, 5}  //no duplicates
//Set(5) {'pizza', 'pasta', 'fries', 'burger', 'cheese'}
//Set(9) {'a', 'b', 'd', 'e', 'l', 'r','h','m','n'}
Enter fullscreen mode Exit fullscreen mode
  • We can get set size like that
  • size of the unique values only
console.log(mySet.size); //3
Enter fullscreen mode Exit fullscreen mode
  • we can also check element is in the set or not
console.log(mySet.has(2));//true 
console.log(mySet2.has('milk'));//false 
Enter fullscreen mode Exit fullscreen mode
  • we can add and delete values from a Set
mySet.add(10);
mySet.delete(2);
console.log(mySet);//{1, 5, 10}
Enter fullscreen mode Exit fullscreen mode
  • there is no way of retrieving values from a set that’s because if all values are unique and if their does not matter there is no point of retrieving values out of a set and if your goal is to actually store values in order then the best use case is an Array

  • we can iterate over a set cause they are iterable as we said before

for(const item of mySet) console.log(item);
// 1
// 5
// 10
Enter fullscreen mode Exit fullscreen mode
  • the main use cause of sets is actually to remove duplicate values from arrays
const arr = [10,10,20,20,30];
const uniqueArr = new Set(arr);
console.log(uniqueArr); //{10, 20, 30}

//if u want to save the unique values to an array again u can use the spread operator like that cause it work on all iterables
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); //[10, 20, 30]
Enter fullscreen mode Exit fullscreen mode
  • and finally u can delete all set element by using clear method
arr.clear();
Enter fullscreen mode Exit fullscreen mode

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

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

Okay