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);
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.
Sign up and receive a free copy immediately.