The following four data structures are new in ECMAScript 6: Map
, WeakMap
, Set
and WeakSet
.
A Set is a collection of unique elements of any type.
Basic usage
Set add and delete:
Set size and clear:
Set has:
It returns boolean value whether an element is present with the given value in the Set object or not.
Iterating Sets
Converting between Array and Set
You can create an Array from a Set using Array.from or the spread operator.
Set objects store unique values, so any duplicate elements from an Array are deleted when converting.
Array Vs Set
- Checking whether an element exists in an collection using indexOf for arrays is slow.
- Set objects let you delete elements by their value. With an array you would have to splice based on a element's index.
- The value NaN cannot be found with indexOf in array.
- Set objects store unique values, you don't have to keep track of duplicates by yourself.