Onze vrijwilligers hebben dit artikel nog niet naar het Nederlands vertaald. Doe mee en help de klus te klaren!
U kunt het artikel ook in het English (US) lezen.

The Set object lets you store unique values of any type, whether primitive values or object references.

Syntax

new Set([iterable]);

Parameters

iterable
If an iterable object is passed, all of its elements will be added to the new Set. If you don't specify this parameter, or its value is null, the new Set is empty.

Return value

A new Set object.

Description

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.

Value equality

Because each value in the Set has to be unique, the value equality will be checked. In an earlier version of ECMAScript specification, this was not based on the same algorithm as the one used in the === operator. Specifically, for Sets, +0 (which is strictly equal to -0) and -0 were different values. However, this was changed in the ECMAScript 2015 specification. See "Value equality for -0 and 0" in the browser compatibility table for details.

Also, NaN and undefined can also be stored in a Set. NaN is considered the same as NaN (even though NaN !== NaN).

Properties

Set.length
The value of the length property is 0.
To count how many elements are in a Set, use Set.prototype.size.
get Set[@@species]
The constructor function that is used to create derived objects.
Set.prototype
Represents the prototype for the Set constructor. Allows the addition of properties to all Set objects.

Set instances

All Set instances inherit from Set.prototype.

Properties

Set.prototype.constructor
Returns the function that created an instance's prototype. This is the Set function by default.
Set.prototype.size
Returns the number of values in the Set object.

Methods

Set.prototype.add(value)
Appends a new element with the given value to the Set object. Returns the Set object.
Set.prototype.clear()
Removes all elements from the Set object.
Set.prototype.delete(value)
Removes the element associated to the value and returns the value that Set.prototype.has(value) would have previously returned. Set.prototype.has(value) will return false afterwards.
Set.prototype.entries()
Returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. This is kept similar to the Map object, so that each entry has the same value for its key and value here.
Set.prototype.forEach(callbackFn[, thisArg])
Calls callbackFn once for each value present in the Set object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the this value for each callback.
Set.prototype.has(value)
Returns a boolean asserting whether an element is present with the given value in the Set object or not.
Set.prototype.keys()
Is the same function as the values() function and returns a new Iterator object that contains the values for each element in the Set object in insertion order.
Set.prototype.values()
Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
Set.prototype[@@iterator]()
Returns a new Iterator object that contains the values for each element in the Set object in insertion order.

Examples

Using the Set object

var mySet = new Set();

mySet.add(1); // Set [ 1 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add('some text'); // Set [ 1, 5, 'some text' ]
var o = {a: 1, b: 2};
mySet.add(o);

mySet.add({a: 1, b: 2}); // o is referencing a different object so this is okay

mySet.has(1); // true
mySet.has(3); // false, 3 has not been added to the set
mySet.has(5);              // true
mySet.has(Math.sqrt(25));  // true
mySet.has('Some Text'.toLowerCase()); // true
mySet.has(o); // true

mySet.size; // 5

mySet.delete(5); // removes 5 from the set
mySet.has(5);    // false, 5 has been removed

mySet.size; // 4, we just removed one value
console.log(mySet);// Set [ 1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2} ]

Iterating Sets

// iterate over items in set
// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} 
for (let item of mySet) console.log(item);

// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} 
for (let item of mySet.keys()) console.log(item);
 
// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} 
for (let item of mySet.values()) console.log(item);

// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} 
//(key and value are the same here)
for (let [key, value] of mySet.entries()) console.log(key);

// convert Set object to an Array object, with Array.from
var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}]

// the following will also work if run in an HTML document
mySet.add(document.body);
mySet.has(document.querySelector('body')); // true

// converting between Set and Array
mySet2 = new Set([1, 2, 3, 4]);
mySet2.size; // 4
[...mySet2]; // [1, 2, 3, 4]

// intersect can be simulated via 
var intersection = new Set([...set1].filter(x => set2.has(x)));

// difference can be simulated via
var difference = new Set([...set1].filter(x => !set2.has(x)));

// Iterate set entries with forEach
mySet.forEach(function(value) {
  console.log(value);
});

// 1
// 2
// 3
// 4

Implementing basic set operations

function isSuperset(set, subset) {
    for (var elem of subset) {
        if (!set.has(elem)) {
            return false;
        }
    }
    return true;
}

function union(setA, setB) {
    var _union = new Set(setA);
    for (var elem of setB) {
        _union.add(elem);
    }
    return _union;
}

function intersection(setA, setB) {
    var _intersection = new Set();
    for (var elem of setB) {
        if (setA.has(elem)) {
            _intersection.add(elem);
        }
    }
    return _intersection;
}

function difference(setA, setB) {
    var _difference = new Set(setA);
    for (var elem of setB) {
        _difference.delete(elem);
    }
    return _difference;
}

//Examples
var setA = new Set([1, 2, 3, 4]),
    setB = new Set([2, 3]),
    setC = new Set([3, 4, 5, 6]);

isSuperset(setA, setB); // => true
union(setA, setC); // => Set [1, 2, 3, 4, 5, 6]
intersection(setA, setC); // => Set [3, 4]
difference(setA, setC); // => Set [1, 2]

Relation with Array objects

var myArray = ['value1', 'value2', 'value3'];

// Use the regular Set constructor to transform an Array into a Set
var mySet = new Set(myArray);

mySet.has('value1'); // returns true

// Use the spread operator to transform a set into an Array.
console.log([...mySet]); // Will show you exactly the same Array as myArray

Relation with Strings

var text = 'India';

var mySet = new Set(text);  // Set ['I', 'n', 'd', 'i', 'a']
mySet.size;  // 5

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Set' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Set' in that specification.
Draft  

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support38121311258
new Set(iterable)381213 No259
new Set(null) Yes123711 Yes9
Set() without new throws Yes124211 Yes9
Key equality for -0 and 0381229 No259
add381213112258
clear38121911258
delete38121311258
entries381224 No258
forEach38122511258
has38121311258
prototype38121311258
size381219311258
values381224 No258
@@iterator Yes Yes

36

27 — 364 5

17 — 276 7

No Yes Yes
@@species511341 No3810
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support38381214258 Yes
new Set(iterable)38381214259 Yes
new Set(null) Yes Yes1237 Yes9 Yes
Set() without new throws Yes Yes1242 Yes9 Yes
Key equality for -0 and 038381229259 Yes
add38381214258 Yes
clear38381219258 Yes
delete38381214258 Yes
entries38381224258 Yes
forEach38381225258 Yes
has38381214258 Yes
prototype38381214258 Yes
size383812193258 Yes
values38381224258 Yes
@@iterator Yes Yes Yes

36

27 — 364 5

17 — 276 7

Yes Yes Yes
@@species5151134138105.0

1. From version 0.10: this feature is behind the --harmony runtime flag.

2. Returns 'undefined' instead of the 'Set' object.

3. From Firefox 13 to Firefox 18, the size property was implemented as a Set.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.

4. A placeholder property named @@iterator is used.

5. Supported as @@iterator.

6. A placeholder property named iterator is used.

7. Supported as iterator.

8. From version 6.0.0: this feature is behind the --harmony runtime flag.

See also