Maps and Sets

Introduction
Unlike programming languages like Python and Java, JavaScript comes with only a few built-in Data Structures. ES2015 tackled this issue by adding in two data structures common in other languages: maps and sets.
In this subunit, we'll teach you what you need to know to get up and running with these two data structures. You'll learn what they are, how to use them, and what kinds of problems they are best suited for. At the end of the subunit, we'll have a few exercises for you to complete.
Data Structure in JavaScript
Data structures are formats for efficiently collecting or storing data
So far we've seen Arrays and Objects
ES2015 introduces two new ones, Maps and Sets
Maps
Also called "hash maps" in other languages
Until ES2015 - objects were replacements for maps
Similar to objects, except the keys can be ANY data type!
Created using the new keyword
What is Looks Like
Keys can be any type!
We can easily iterate over the map!
Maps also provide:
.keys()
to iterate over all the keys.values()
to iterate over all the values.entries()
to iterate over all the [key,value] pairsa Symbol.iterator which means we can use a for...of loop to iterate over the keys, values or both!
Here's what it looks like to access everything in a map with .entriesQ and destructuring!
Why use maps
Finding the size is easy - no more loops or Object.keys()
The keys can be any data type!
You can accidentally overwrite keys on the Object.prototype in an object you make - maps do not have that issue
Iterating over keys and values in a map is quite easy as well
If you need to look up keys dynamically (they are not hard coded strings)
If you need keys that are not strings!
If you are frequently adding and removing key/value pairs
Are key-value pairs frequently added or removed?
If you are operating on multiple keys at a time
Sets
All values in a set are unique
Any type of value can exist in a set
Created using the new keyword
Exist in quite a few other languages, ES2015 finally brings them to JavaScript
Creating Sets
To make a new Set, we call new Set()
When making a new Set, you can also pass in an iterable object,
Adding to Sets
There is only a single method to add items to a set: add()
size
Use the size property to determine the number of values stored in a Set:
Checking for an element in the Set
Sets do not support random access,
but we are able to check if a set contains a given value using has()
Removing values in a set
To remove a single value from a set, use delete()
We can also use clear() to empty a set of all values:
Iterating over a set
Sets are iterable objects, so we can use them with for...of loops or the spread operator
Values in a set are ordered by insertion order. Here's one example of looping over a Set:
When you use sets
Removing duplicate values
Uniqueness required
Efficiently checking if an item is in a collection (much better than arrays)