Quick Dive Into JavaScript Sets

04/17/22

Intro

So you've heard about this thing called "Sets" in JavaScript, but you're not sure you need them. Today, I'm going to quickly show you two examples of how you can use them. The first example is something that you might come across in your daily tasks, while the second one is a little more fun. Hopefully these examples will give you idea's of where you can start using Set's in your own JavaScript code.

Extracting Only Unique Values

Sets are used to store unique values, which means if you try to add a value that is already in a Set, nothing will happen. For example, let's say we have the string aaabcdddeefffffgz, and we want to create a new string with all of the duplicates removed. We can easily use a Set to filter out all of the duplicates. We can do so by converting the string to a Set, converting the Set to an array, and joining it back into a string.

const str = 'aaabcdddeefffffgz'
const set = new Set(str)
const newStr = [...set].join('')

console.log(newStr) // 'abcdefgz'

It would be nice if you could directly convert a set back into a string, but unfortunately the Set object does not have a method for this.

Does A String Contain All The Letters Of The Alphabet?

This one is a little more fun, and super easy to do with a set.

const hasAllLetters = (str) => {
  return new Set(str).size === 26
}

hasAllLetters('I went to the store to grab some milk') // false
hasAllLetters('abcdefghijklmnopqrstuvwxyz') // true

We throw the string into a Set, and then check to see if it's size is equal to 26, which is how many numbers are in the alphabet. Easy peasy!

Summary

That's pretty much it on my end. I will now send you upon your merry way to the offical Set documents on MDN. If you have any problems understanding any of this, feel free to shoot me a message, and I'll make sure it's crystal clear.

Want To Level Up Your JavaScript Game?

Book a private session with me, and you will be writing slick JavaScript code in no time.