loading...
Cover image for JavaScript Sets are Excellent!

JavaScript Sets are Excellent!

jacobmgevans profile image Jacob Evans ・2 min read

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: `meow`, 1: `hundred` }<br>
console.log(object.hasOwnProperty(`cat`))<br>
console.log(object.hasOwnProperty(`1`))

  • 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(`2`)) // 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(`431242`)) // 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 😎
🚧🚧🚧🚧

Posted on by:

jacobmgevans profile

Jacob Evans

@jacobmgevans

Associate Software Engineer @ JP Morgan & Chase | Air Force Veteran | Hardware Enthusiast | Outdoorsman | INTJ | Create React App contributor

Discussion

markdown guide
 

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]));

 

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

 

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 :(

All awesome implementations!!

 

Fair point I forgot about the space.

 
 

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

 

What's confusing maybe I can help?

 

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?

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)

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...

 
 

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

 
 

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