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

var valueSet = new Set([1,2,2,3]);
console.log(valueSet); // [1,2,3]

Set add and delete:

var valueSet = new Set();
valueSet.add(1);
valueSet.add("green");
console.log(valueSet); // 1, "green"
valueSet.delete("green");
console.log(valueSet); // 1

Set size and clear:

var valueSet = new Set([3, 7]);
console.log(valueSet.size); // 2
valueSet.clear(); // Removes all elements from the Set object.
console.log(valueSet.size); // 0

Set has:

It returns boolean value whether an element is present with the given value in the Set object or not.

var valueSet = new Set([3, 7]);
console.log(valueSet.has(3)); // true
console.log(valueSet.has(31)); // false

Iterating Sets

var valueSet = new Set([1,2,2,3]);
for (let item of valueSet) {
    console.log(item);
}
// 1
// 2
// 3

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.

var valueSet = new Set([1,2,3,3,true]);
console.log(valueSet); // Set {1, 2, 3, true}
var array = Array.from(valueSet);
var array1 = [...valueSet];
console.log(array); // [1, 2, 3, true]
console.log(array1); // [1, 2, 3, true]

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.