Set and Map in ES6
Set and Map are new data structures introduced in ES6.
- Set stores unique values.
- Map stores key-value pairs.
1. Set
A Set is a collection of unique values.
Creating a Set
Use new Set() to create a Set.
Adding Values — add()
Use add() to add values to a Set.
Output:
Duplicate Values
A Set does not store duplicate values.
Output:
The value 10 is stored only once.
Checking a Value — has()
Use has() to check whether a value exists.
Output:
Output:
Removing a Value — delete()
Use delete() to remove a value.
Output:
Removing All Values — clear()
Use clear() to remove all values.
Output:
Getting the Size — size
The size property tells us how many values are in the Set.
Output:
Note: size is a property, not a method.
Set from an Array
We can create a Set from an array.
Output:
This is useful for removing duplicate values.
Converting Set to Array
We can convert a Set back to an array using the spread operator.
Output:
2. Map
A Map stores data in key-value pairs.
For example:
Creating a Map
Use new Map().
Adding Data — set()
Use set() to add key-value pairs.
Output:
Getting Data — get()
Use get() to get the value of a key.
Output:
Output:
Checking a Key — has()
Use has() to check whether a key exists.
Output:
Output:
Removing Data — delete()
Use delete() to remove a key-value pair.
The age key and its value are removed.
Removing All Data — clear()
Use clear() to remove all key-value pairs.
Output:
Getting the Size — size
The size property tells us how many key-value pairs are in the Map.
Output:
Set vs Map
Feature | Set | Map |
|---|---|---|
Stores | Unique values | Key-value pairs |
Add data |
|
|
Get data | Not available |
|
Check |
|
|
Remove |
|
|
Remove all |
|
|
Count |
|
|
Easy Rule
Example:
Important Methods
Set
Map