How to Create a Set from an Array in JavaScript

Last updated on June 08, 2022
How to Create a Set from an Array in JavaScript

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);
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also