logo

NJP

Maps and Sets - Let's Learn ECMAScript 2021 with Earl Duque

Import · Jan 25, 2024 · video

Okay. So in this lesson, we're going to be
talking about maps and sets, very important functionality
that was added into JavaScript. Both of these are structures that enhance
the way we can store and manipulate data. They are a lot more flexible and efficient compared to traditional objects
and arrays. A map is a collection of key value pairs
where the keys can be of any type. So that's a little bit more versatile
than objects. A Set on the other
hand, is a collection of unique values of any type, making it perfect
for storing non repetitive data. So to create a map, you use the syntax, new Map. And then from there you add to the map via the set method. So incidentMap.set
and then you populate the map . To retrieve a value. Instead of using set, we use get. Let me run this. There's the value
we set for incident001 To iterate over maps, you can use the for each method. And if I run that, And there you go. Each key value pair is iterated over. The fun part about maps is that it
doesn't have to be a string for the key. So if I have an array set to x and I provide x in here, you can see that one of the keys is now
an entire array. And likewise, if I want to get that value
for that array key, I can just provide that array again to find that value. On the flip side, there's sets. so if I create a unique
set variable and set it as set, I guess we can start adding things to it. So if I say unique set dot add in one and I'm going to go ahead
and copy this a few times and I'll even add a duplicate here, we can see that if I check the size of this set, so uniqueSet.size and I run that script,
it's actually only three. Because what's cool about set
is it automatically ignores if there are duplicates and just like map,
we can actually put any types in here. So this could be an array. This could be an object. This could be a other
it could be any data type basically. And it always checks to see if each thing
has been placed inside of it is unique and then throws out any duplicates
automatically. So in practical use,
that means when you're creating a script and you know you may be getting duplicate
values that you want to throw out, then you can use sets
instead of using arrays or objects and doing an if statement to check
if that thing exists or not first, set can just do that automatically. And if you want to iterate
through your set, you can do things like let incident of uniqueSet and then log a statement of each incident and run that script. And there you go. It's showing each of the different items
that were added into that set.

View original source

https://www.youtube.com/watch?v=C9YpxVWsl-4