To create a Set
from an array in JavaScript, pass the array to the Set()
constructor. For example:
const arr = [1, 2, 3];
const set = new Set(arr);
console.log(set); // Set(3) { 1, 2, 3 }
console.log(set.has(2)); // true
set.delete(2);
console.log(set); // Set(2) { 1, 3 }
A Set
object only stores unique values, so it won’t contain any duplicates.
const arr = [1, 1, 2, 3, 3, 4];
const set = new Set(arr);
// Set(4) { 1, 2, 3, 4 }
console.log(set);
This makes it useful for removing duplicate elements from an array without mutating it, for example:
const arr = [1, 1, 2, 3, 3, 4];
const distinct = Array.from(new Set(arr));
// [1, 2, 3, 4]
console.log(distinct);
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.
Sign up and receive a free copy immediately.