How to Create a New Set From a JavaScript Array?

The Set constructor allows you to pass an iterable (such as an array) as an argument (which adds all unique elements of the iterable to the new Set). For example:

const arr = [ 'foo', 'bar', 'baz' ];
const set = new Set(arr);

console.log(set); // Set(3) {"foo", "bar", "baz"}

Since Set objects only store unique values, duplicates in the array are not added. For example:

const arr = [ 'foo', 'foo', 'bar', 'foo', 'baz' ];
const set = new Set(arr);

console.log(set); // Set(3) {"foo", "bar", "baz"}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.