DEV Community

Cover image for JavaScript Sets are Excellent!
Jacob Evans
Jacob Evans

Posted on

JavaScript Sets are Excellent!

Sets In JavaScript Are πŸ”₯

  • In MDN Set it states "The Set object lets you store unique values of any type, whether primitive values or object references."

So the obvious use case for Sets, removing duplicates! Which they do very easily and concisely. I personally like the example I created for the banner. The combination of spread ... and new Set() inside of an array literal consuming input from the function, meaning it will take in any iterable that can be spread "dedupe" it and return those values in an array! Super cool!! A lot going on in a small package.

Quasi-Typecheck/searching & searching & deleting

  • Sets in JavaScript have some things Arrays don't have and are missing some things Arrays do have... Example, Sets have no index! "But I thought you said it was iterable?" I did, that doesn't mean it has an Index πŸ˜†

  • Ok, so what is one of the most useful things all iterables share! I want to know it "has" πŸ˜† something, with Objects .hasOwnProperty() will check if something exists but not if the type matches...
    const object = { cat:  raw `meow` endraw , 1:  raw `hundred` endraw  }<br>
console.log(object.hasOwnProperty( raw `cat` endraw ))<br>
console.log(object.hasOwnProperty( raw `1` endraw ))

  • So... Not only does the .has() from Sets check work a little differently than the one from .hasOwnProperty() but it also works a bit differently than .includes() from arrays but both .has() & .includes() will return false of the type does not match what is being search for.
    const mySet = new Set([1, 2, 3, 4])<br>
console.log(mySet.has( raw `2` endraw )) // false<br>
console.log(mySet.has(2)) // true

  • The next super useful thing from built-in of Sets and there isn't the equivalent in Arrays is .delete() which in Arrays you either know the index or search for and get the index of the element then work out how to remove it.

    • What does Set .delete() look like in comparison? const mySet = new Set([1, 2, 1223, 431242, 342345245235, 2123123, 12313])
console.log(mySet.delete(2)) // true
console.log(mySet.delete(342345245235)) // true
console.log(mySet.delete( raw `431242` endraw )) // false
console.log(mySet); // Set { 1, 1223, 431242, 2123123, 12313 }

A great resource to read on Sets as well!
https://medium.com/front-end-weekly/es6-set-vs-array-what-and-when-efc055655e1a

🚧🚧🚧🚧
More to come on Set use cases and examples, with explanations 😎
🚧🚧🚧🚧

Top comments (15)

Collapse
 
averyferrante profile image
Joseph Avery Ferrante • Edited

Cool read!

Fun 'interview style' question that can utilize sets:
Return an array of unique characters from the string 'Hello World', excluding spaces:

*** MY ANSWER ***

new Set('hello world'.split(' ').reduce((acc, cur) => acc.concat([...cur]), []));

  • OR using new flatMap operator -

new Set('hello world'.split(' ').flatMap(cur => [...cur]));

Collapse
 
bushblade profile image
Will Adams

Cool I guess you could also do
[...new Set([...'Hello World'])]

Collapse
 
jamesthomson profile image
James Thomson

Almost, it won't exclude the space so you'd have to do something like [...new Set([...'Hello World'.replace(/\s/g, '')])] which kinda ruins how nice and concise this was :(

Thread Thread
 
jacobmgevans profile image
Jacob Evans

All awesome implementations!!

Collapse
 
bushblade profile image
Will Adams

Fair point I forgot about the space.

Collapse
 
jacobmgevans profile image
Jacob Evans

Thanks! :)

Collapse
 
seanmclem profile image
Seanmclem • Edited

I've been pretty impressed by the potential of sets before. I feel a little confused

Collapse
 
jacobmgevans profile image
Jacob Evans

What's confusing maybe I can help?

Collapse
 
seanmclem profile image
Seanmclem

I'd seen them used before to make iterable objects of some kind. I didn't fully understand it. But here you're using it to remove duplicates from an array. Is this the intended behavior of sets?

Thread Thread
 
jacobmgevans profile image
Jacob Evans

It is not the only intended use for Sets, they are also wicked fast and efficient at locating elements to see if they exist and deleting elements. Both are built-in functionality for Sets. I like to think of sets as almost a Hybrid of Maps and Arrays, its a bit of an oversimplification and generalization but I personally like thinking about them in that way.

One major difference is Arrays are Indexed collections while Sets are Keyed collections, which allows for some of the behaviors I mentioned that are similar to Maps like .has and .delete() and also related to why duplicates are not allowed (Maps also can't have duplicates)

Thread Thread
 
seanmclem profile image
Seanmclem

I didn't know that map was its own type of object - in addition to a function on an array
developer.mozilla.org/en-US/docs/W...

Collapse
 
khangprcvn profile image
khangprcvn

Thanks for sharing

Collapse
 
jacobmgevans profile image
Jacob Evans

Happy too! I plan on adding more to the article so stay tuned lol

Collapse
 
jethrolarson profile image
Jethro Larson

Also cool are the new methods in draft to be added to the language: github.com/tc39/proposal-set-methods

Collapse
 
jacobmgevans profile image
Jacob Evans

Thank you! 😁