Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Set

A collection of unique values.

Available since: ES2015

Syntax

new Set(iterable)

Parameters

ParameterTypeDescription
iterableIterableOptional. An array or another collection to start with.

Return value

SetA new set.

Examples

Duplicates are removed automatically:

const tags = new Set(['js', 'css', 'js']);
 
console.log(tags.size);

Output:

2

The unique elements of an array:

const numbers = [3, 1, 3, 2, 1];
 
console.log([...new Set(numbers)].join(', '));

Output:

3, 1, 2

Notes

Uniqueness is checked like ===, so identical-looking objects count as different. The order is the insertion order.

See also

  • Set.prototype.add — Adds a value to a Set if it is not there yet.
  • Set.prototype.has — Checks whether a value is in a Set.
  • Map — A collection of key–value pairs where a key can be anything.
  • Array.from — Creates an array from a string, Set, Map or another iterable.

Related recipes

In the tutorial

  • Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.

Thanks for reading!

Donate to the site — we work hard for you.