Check out a free preview of the full Four Semesters of Computer Science in 5 Hours course:
The "Set Data Structure" Lesson is part of the full, Four Semesters of Computer Science in 5 Hours course featured in this preview video. Here's what you'd learn in this lesson:

- A set is a data structure than has four basic operations: Items can be added, items can be removed, a “contains" method can verify an item’s existence, and the set can return a list of it’s items.

Get Unlimited Access Now

Transcript from the "Set Data Structure" Lesson

[00:00:00]
>> [MUSIC]

[00:00:03]
>> Brian Holt: Back to data structures. A set has no order, a set is not a list. So first of all let's get out of the way, a set and an array totally not the same. It's more of an object and you can think of a set like a just this amorphous cloud that you have.

[00:00:23]
>> Brian Holt: So, you have this like a amorphous cloud and you're going to be putting stuff into it. So, I'm gonna call, set.add(5) or something like that, right. And so, it's just going to put five somewhere in this amorphous cloud and then I'm gonna say, same thing I'm going to call with 7 or something like that, and puts it into, the again to the amorphous cloud.

[00:00:49] So something to know about the set is it has no duplicate. If I call add the 7 again, depending on what implementation you're using, it's just going to do nothing because it's already there, or it's going to error or something else, right. So one, it's very useful if you have a a large set of numbers that you need to deduplicate.

[00:01:10] You can just add them all to the set, and then at that point you guaranteed that you have no duplicates in there. [COUGH] Let's see what else, [INAUDIBLE] there. And the other thing is, let's say, you have a list of user names, and you obviously you cannot duplicate user names, so you can say you have a set of user names.

[00:01:33] So if I register BT Holt as my username and then some other jerk tries to register BT Holt as well, it's gonna say well does the set already contain BT Holt? Yes, okay, well you can't have that right. That's another useful ability of sets. So basically they do add, removes and contains and then toList whatever.

[00:01:55] Basically toList just say give me a dump of everything in there, but remember that there's no sense of order. So some sets would give it to you in the order that you added it to it and other sets was just give it to the order that it stores it in, whatever way it decides to do.

[00:02:08] Another ones are just gonna give it to however it wants to, but the important to know is that sets have no guarantee of order.
>> Brian Holt: Yeah, cool. Any questions about sets?
>> Brian Holt: JavaScript now actually does have native sets as of ES6. So you can create a new set and use it.