Complete Guide to JS Sets: How They Work & When To Use Them

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
every one today we're talking about sets in JavaScript just a quick note up front I'm working hard to put out one to two videos a week for the next few months a little experiment so please subscribe if you're interested in seeing those updates but also if you have any ideas or suggestions for videos you'd like please leave a comment this video on sets is the result of a comment that someone left last week lastly I'll have an update on my baby chicks little chickens at the end of the video if you care let's get started alright so here are the notes I made for the video you can find the link in the description I'm trying to post more one to two times a week for the next couple months but I cannot promise I'll have these detailed notes for every single video but here they are and there's a lot of stuff here we're gonna go through all of it we'll start with the basics what our sets wide what do you need to know about them what are the main methods properties the things we might want to do with them and then we'll finish up by talking about why would you use them what situations are they better than something like an array and I'll show you a couple of examples let's start with very basics sets are a data structure a new ish data structure they allow you to store a collection of values those values can be anything but the really really important thing you must know the single most important thing about sets is they only store unique values and sets often get lumped in with arrays because they are collections of data there's an order to a set but the order is nowhere near as important as it is to an array arrays are indexed so every item has a corresponding index we can retrieve elements using that index sets are different they are ordered by insertion order and sets do not support random access meaning we can't say give me the last item or the first item or the tenth item in this set in addition we can't reorder sets and there are far fewer features and methods in a set compared to array if we look at the docs for array on mdn tons and tons of methods over here maybe 3040 methods but if we look at sets we've got like seven or eight so far far fewer methods that are much simpler but they can be very powerful in certain situations which we'll get into and before I forget let's talk about browser compatible this is actually pretty good these days as always Internet Explorer has some red but usually it's a lot more red when we talk about newer features in JavaScript so I'll point out as we go certain things that won't work in IE so as I said sets are a collection of unique values and the first thing we need to do is learn how to make a new set unfortunately there is no set literal or shortcut syntax you know to make an array we could do new array like that or we can just do square braces with a set our only option is new set and that makes us a new set so that makes it completely empty set we can save it to a variable what we can also do is pass in an iterable so for example an array here is an array of two items and those two values will be added to the set so the iterable item we pass in will be iterated over each value in it is added to the set and that's really the only way we can initialize a set so we can't do something like this we can't pass it in a number it tells us number one is not iterable we can't do true or false we can't try passing in a bunch of numbers as different arguments what we can do is pass in an indoor pool like an array or if you wanted to even a string so we could do dog and that gives us a set with three items it iterates over the string for each character and adds each character in as a value in the set also note that this iterable syntax is not supported in IE it was one of those red pieces right here in Internet Explorer you can only do new set and initialize it with no values and then you can go back and add one at a time so let's see how we do that to add items in it's really easy there is an ADD method so let's try it over here I'm going to make a new variable annoying hash tags equals new set and I'll initialize it with two values well one value an array which is iterated over to add two values to our set and we end up with two values so to add one in we just call dot add and I can pass one more in here let's do a string again I don't have to only store strings but it makes sense in this case we're storing hashtags now I have three items so ad works differently than this right here when we initialize a set if we pass in an iterable it iterates over it when we add to a set whatever we pass to it will be added in its entirety it's not iterated over if I try to do something like Yolo again there's no error but you can see our set does not grow remember sets are collections of unique values so we can't have a duplicate now I could add in something like the number 12 that's added in I could add true if I try and add true again it's not added we already have true also if I add an array as I kind of talked about already that entire array is added as an item you can see it here okay so that's add nice and simple so if we want to know how many items are in a set we use size we don't use the length we use size so come over here annoying hash tags dot size well if I can spell it right and there we go that's all there is to it it's just a property not a method it's a property next up let's talk about a method called has so has is a boolean method and it tells us if a set contains a given value or not it's really nice and easy and it's actually very very fast we'll talk about it in just a bit well at the end of the video compared to checking if a value is contained inside of an array has is really efficient so if I wanted to check does this annoying hash tags contain does it have Yolo I would do this it does does it contain the hash tag foody it does not now what's great about sets compared to arrays is that if you saw my big o-notation video this will make more sense sets are oh of one they are constant time to figure out if a value is in a set to run the has method if you compare that to an array if we instead had an array let's just do numbers for a moment here's some random numbers if I want to know if this array contains the number 1 I could use index of for example or the newer includes method JavaScript is going to have to check every item and look for one ru 1 ru 1 ru 1 and so on and that could be at the very end of the array it could not be in the array but it's going to have to check the entire thing so as my array grows if I have 10,000 items in here and I'm looking for one the number of operations it takes grows with the size of the array sets are different it might seem like they work in the same way that in order to tell if Yolo is in here we would have to check every single item but in reality the way that sets are implemented is they use something called a hash map where Yolo is run through a hashing function and I don't want to go overboard here I'll do a separate video on it all you need to know is that it basically takes a single operation to tell if yo lo or any other value is already in the set it's much much faster next up we can talk about removing values there's two ways really we can delete a single value using delete so I can show that here let's delete true so annoying hash tags dot delete true and if we look at a knowing hash tags now we can see it doesn't contain true and then the second way of deleting things is clear so the clear method is really simple it just empties the entire thing so annoying hash tags clear just gives us an empty set it's the same set we had before it's just been cleared out of everything so said 0 it's empty and that's pretty much it for clear the last feature we'll talk about is that sets are iterables they are interval objects so we can use them with things like for loops for of loops the spread operator so the first thing you should know is that sets are technically ordered they are ordered by the order you insert things in insertion order add something to the beginning or the middle you're only adding to the end so here's a simple four of loop I have annoying hashtags again I put in some of the hashtags I really hate I don't like hashtags in general but these are the ones that annoy me on Instagram and other websites so we added selfie blest and no filter the set has three items in it three values and I can run a four of Floop so four let vowel of annoying hashtags console dot log please don't use each value so it looks like this when we run it please don't use selfie please don't use hashtag blessed same thing for no filter alright so that's the basics of sets as far as the API there's really not much to it so now let's talk about the real important thing why would you use them so they are not a replacement for arrays in general they are a replacement for arrays in very specific situations so kind of the things I think about if I'm considering using a set one you're working with unique values or you need to get unique values from a non unique data set and I spent a little bit of time thinking about when I tend to use sets and here's a couple of situations the first is a really simple easy one when I have non unique data and I want to quickly remove duplicates so this is a very simple example I'll show you something more realistic in just a moment I have an array called missed calls it contains names of people who let's say called me in the last 24 hours and there are duplicates if I quickly wanted to get the unique callers figure out how many people called me in total not the total number of calls I could use a set if I didn't use the set I would need to iterate over the array I would need to keep track of for example Kevin and put that somewhere and then as I iterate 'add each name I would need to check have I already seen this one have I seen this one have I seen this one oh I've already seen Kevin ignore that I've already seen Kevin I've already seen Stevie and so on but if I use a set it's really really easy I can just do new set missed calls and if I wanted that to be an array instead I can use spread I have a video on that from last week to get it back to an array so here's a more realistic example this is from an app I built for one of my courses earlier this year it's a Yahtzee game if you're not familiar with Yahtzee basically you roll five dice and each die can be one to six so let's say this is a hypothetical die roll one five five three two that could be a roll of dice there's five of them they go from one to six each and we need to evaluate if this is a particular hand if it's a five of a kind a four of a kind a straight a full house and we can use sets to make that very easy so for example a full house is two of one kind and three of another so we could have something like this this is a full house we have three fours and two fives so to evaluate that we can use a set to help us out as you can see up here we just make a new set and we check if this size is two because that tells us out of these five elements the five dice there are two unique numbers meaning you have three of one and two of another or to check if there's a five of a kind like one one one one one we just make it a set and check if the size is exactly one and the last one is a little more complicated is large straight meaning that we have five consecutive numbers so we could have something like this right here where we have one two three four and five but if instead we had this this is not a large straight it's one two three four and then no five but a six so to test that out let me go back to a valid one I am first checking that the size of the set is five that's the first bit we need to make sure there are five unique numbers in here but also we need to make sure there's only a 1 or a 6 there is no valid straight that includes both 1 and 6 because we only have 5 slots so I'll quickly test this out we'll do is Full House give it an invalid full house like that we get false but if I make it a valid full house like this we get true we can do is large straight and we could have for example 6 4 3 5 2 that is a valid Straight But if instead I have one it's not valid so this is a real example from something I was doing recently using a set really helps me out to quickly figure out how many unique values are in the dice now there's a second common use case that I found at least in my own life when I'm storing unique data and want to easily check other values against that unique data so the example that I was working on while back was a tags input in a react app where users could type a tag and hit comma and it would create a new tag for them but with tags you can't tag a video or a post with the same thing twice so if you add HTML for example it's already in there so it's not going to be added so that's very easy to do using asset now this is not a full react implementation I wanted to make this video sort of framework agnostic I'm actually probably going to build that tags input in a separate video intro to react video but this is sort of modeling it I have a class called tags input we have a set that we're using to keep track of the tags and every time you add a new tag we just call set add and then we're going to print out the tags so if we tried let's run this first if I tried to do input add tag of HTML the first time through your tags our HTML if I tried to do CSS your tags are HTML and CSS if I try and add HTML again it's unchanged so this is very simple but this is essentially what I was doing in this react app where I'm using a set to figure out what to actually render here now to wrap up I'd like to talk about the time complexity basically how fast the efficiency of sets vs. arrays and this is really just for to operations that I want to talk about first is insertion and then second is searching or checking to see if a value is present so asking does this array have a 5 or just this set have a 5 as you can see here if you don't know Big O notation by the way I do have a video on that but also this is going to be very simple and straightforward sets are fast they're very fast at inserting new values and checking if a set has a value a raise on the other hand are not as fast depending on how you add to an array if you push the end it's fast if you are pushing or if you're unsure if you're adding to the very beginning everything has to get moved over everything gets shifted over and gets a new index and that is slow same thing for checking if a value is present in an array it takes a long time if you have a thousand elements you would potentially need to look in 1,000 different spots and that's why it n has the size of the array grows n the amount of time it takes to search also grouse sets are different because of how sets are implemented with hashmaps when we want to check if a value is present the set is not checking every other value it's doing one operation so here is a quick benchmark I put together this is not very official I'm just using counsel time if you're not familiar with it it's really not that precise but as you'll see here it doesn't really matter because the difference is so stark so what I'm doing I have two functions first I generate a really long array this is what a hundred no this is a million elements so a million elements in an array each one a random number from zero to 4,000 so there are definitely duplicates in that 1 million numbers and what I want to do with that Million number array is create a list of unique numbers so using a set it's super simple I just create a new set with those numbers with an array it's a little different I need to make sure that if I'm pushing to the array that value is not already in the array so I made a little class to help me I have a property called values which is where I'm storing the actual values and array I look for index of so does one number exists in this array already if it doesn't then we'll push that number on but if we get to a duplicate number then we don't do anything so I'm doing the same thing I'm building a set of unique numbers from this array or an array of unique numbers and if I run this right now you can see our set already finished 26 milliseconds the array took 2575 milliseconds all right so thanks for watching here are my baby chicks a week later they're growing very fast and they're looking kind of awkward right now with their fuzziness their feet are sort of horrifying to look at you look too closely those weird feathers but they're kind of adorable this one in particular I don't know their sex he had a female or female but I call this one junior and he or she is very cute and loves to eat from my hand and falls asleep in my hand anyway if you enjoyed this video blah blah blah you know what I'm gonna say please like it subscribe leave a comments I really appreciate it I'm trying to put more weight behind this YouTube thing I can't do it full-time we've got a couple other jobs and things going on but I'm doing my best to devote a couple days a week to making these videos so I appreciate it have a good day and bye
Info
Channel: Colt Steele
Views: 8,892
Rating: 4.9946094 out of 5
Keywords: js, es2015
Id: 4pRkrVwpLQo
Channel Id: undefined
Length: 18min 38sec (1118 seconds)
Published: Tue Aug 13 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.