Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Set

BaselineWidely available *

TheSet object lets you store unique values of any type, whetherprimitive values or object references.

Description

Set objects are collections of values. A value in the setmay only occur once; it is unique in the set's collection. You can iterate through the elements of a set in insertion order. Theinsertion order corresponds to the order in which each element was inserted into the set by theadd() method successfully (that is, there wasn't an identical element already in the set whenadd() was called).

The specification requires sets to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

Value equality

Value equality is based on theSameValueZero algorithm. (It used to useSameValue, which treated0 and-0 as different. Checkbrowser compatibility.) This meansNaN is considered the same asNaN (even thoughNaN !== NaN) and all other values are considered equal according to the semantics of the=== operator.

Performance

Thehas method checks if a value is in the set, using an approach that is, on average, quicker than testing most of the elements that have previously been added to the set. In particular, it is, on average, faster than theArray.prototype.includes method when an array has alength equal to a set'ssize.

Set composition

TheSet object provides some methods that allow you to compose sets like you would with mathematical operations. These methods include:

MethodReturn typeMathematical equivalentVenn diagram
A.difference(B)SetABA\setminus BA Venn diagram where two circles overlap. The difference of A and B is the part of A that is not overlapping B.
A.intersection(B)SetABA\cap BA Venn diagram where two circles overlap. The intersection of A and B is the part where they overlap.
A.symmetricDifference(B)Set(AB)(BA)(A\setminus B)\cup(B\setminus A)A Venn diagram where two circles overlap. The symmetric difference of A and B is the region contained by either circle but not both.
A.union(B)SetABA\cup BA Venn diagram where two circles overlap. The union of A and B is the region contained by either or both circles.
A.isDisjointFrom(B)BooleanAB=A\cap B = \emptyA Venn diagram with two circles. A and B are disjoint because the circles have no region of overlap.
A.isSubsetOf(B)BooleanABA\subseteq BA Venn diagram with two circles. A is a subset of B because A is completely contained in B.
A.isSupersetOf(B)BooleanABA\supseteq BA Venn diagram with two circles. A is a superset of B because B is completely contained in A.

To make them more generalizable, these methods don't just acceptSet objects, but anything that'sset-like.

Set-like objects

Allset composition methods requirethis to be an actualSet instance, but their arguments just need to be set-like. Aset-like object is an object that provides the following:

  • Asize property that contains a number.
  • Ahas() method that takes an element and returns a boolean.
  • Akeys() method that returns aniterator of the elements in the set.

For example,Map objects are set-like because they also havesize,has(), andkeys(), so they behave just like sets of keys when used in set methods:

js
const a = new Set([1, 2, 3]);const b = new Map([  [1, "one"],  [2, "two"],  [4, "four"],]);console.log(a.union(b)); // Set(4) {1, 2, 3, 4}

Note:The set-like protocol invokes thekeys() method instead of[Symbol.iterator]() to produce elements. This is to make maps valid set-like objects, because for maps, the iterator producesentries but thehas() method takeskeys.

Arrays are not set-like because they don't have ahas() method or thesize property, and theirkeys() method produces indices instead of elements.WeakSet objects are also not set-like because they don't have akeys() method.

Set-like browser APIs

BrowserSet-like objects (or "setlike objects") areWeb API interfaces that behave in many ways like aSet.

Just likeSet, elements can be iterated in the same order that they were added to the object.Set-like objects andSet also have properties and methods that share the same name and behavior.However unlikeSet they only allow a specific predefined type for each entry.

The allowed types are set in the specification IDL definition.For example,GPUSupportedFeatures is aSet-like object that must use strings as the key/value.This is defined in the specification IDL below:

webidl
interface GPUSupportedFeatures {  readonly setlike<DOMString>;};

Set-like objects are either read-only or read-writable (see thereadonly keyword in the IDL above).

The methods and properties have the same behavior as the equivalent entities inSet, except for the restriction on the types of the entry.

The following are examples of read-onlySet-like browser objects:

The following are examples of writableSet-like browser objects:

Constructor

Set()

Creates a newSet object.

Static properties

Set[Symbol.species]

The constructor function that is used to create derived objects.

Instance properties

These properties are defined onSet.prototype and shared by allSet instances.

Set.prototype.constructor

The constructor function that created the instance object. ForSet instances, the initial value is theSet constructor.

Set.prototype.size

Returns the number of values in theSet object.

Set.prototype[Symbol.toStringTag]

The initial value of the[Symbol.toStringTag] property is the string"Set". This property is used inObject.prototype.toString().

Instance methods

Set.prototype.add()

Inserts a new element with a specified value in to aSet object, if there isn't an element with the same value already in theSet.

Set.prototype.clear()

Removes all elements from theSet object.

Set.prototype.delete()

Removes the element associated to thevalue and returns a boolean asserting whether an element was successfully removed or not.Set.prototype.has(value) will returnfalse afterwards.

Set.prototype.difference()

Takes a set and returns a new set containing elements in this set but not in the given set.

Set.prototype.entries()

Returns a new iterator object that containsan array of[value, value] for each element in theSet object, in insertion order. This is similar to theMap object, so that each entry'skey is the same as itsvalue for aSet.

Set.prototype.forEach()

CallscallbackFn once for each value present in theSet object, in insertion order. If athisArg parameter is provided, it will be used as thethis value for each invocation ofcallbackFn.

Set.prototype.has()

Returns a boolean asserting whether an element is present with the given value in theSet object or not.

Set.prototype.intersection()

Takes a set and returns a new set containing elements in both this set and the given set.

Set.prototype.isDisjointFrom()

Takes a set and returns a boolean indicating if this set has no elements in common with the given set.

Set.prototype.isSubsetOf()

Takes a set and returns a boolean indicating if all elements of this set are in the given set.

Set.prototype.isSupersetOf()

Takes a set and returns a boolean indicating if all elements of the given set are in this set.

Set.prototype.keys()

An alias forSet.prototype.values().

Set.prototype.symmetricDifference()

Takes a set and returns a new set containing elements which are in either this set or the given set, but not in both.

Set.prototype.union()

Takes a set and returns a new set containing elements which are in either or both of this set and the given set.

Set.prototype.values()

Returns a new iterator object that yields thevalues for each element in theSet object in insertion order.

Set.prototype[Symbol.iterator]()

Returns a new iterator object that yields thevalues for each element in theSet object in insertion order.

Examples

Using the Set object

js
const mySet1 = new Set();mySet1.add(1); // Set(1) { 1 }mySet1.add(5); // Set(2) { 1, 5 }mySet1.add(5); // Set(2) { 1, 5 }mySet1.add("some text"); // Set(3) { 1, 5, 'some text' }const o = { a: 1, b: 2 };mySet1.add(o);mySet1.add({ a: 1, b: 2 }); // o is referencing a different object, so this is okaymySet1.has(1); // truemySet1.has(3); // false, since 3 has not been added to the setmySet1.has(5); // truemySet1.has(Math.sqrt(25)); // truemySet1.has("Some Text".toLowerCase()); // truemySet1.has(o); // truemySet1.size; // 5mySet1.delete(5); // removes 5 from the setmySet1.has(5); // false, 5 has been removedmySet1.size; // 4, since we just removed one valuemySet1.add(5); // Set(5) { 1, 'some text', {...}, {...}, 5 } - a previously deleted item will be added as a new item, it will not retain its original position before deletionconsole.log(mySet1); // Set(5) { 1, "some text", {…}, {…}, 5 }

Iterating sets

The iteration over a set visits elements in insertion order.

js
for (const item of mySet1) {  console.log(item);}// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5for (const item of mySet1.keys()) {  console.log(item);}// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5for (const item of mySet1.values()) {  console.log(item);}// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5// key and value are the same herefor (const [key, value] of mySet1.entries()) {  console.log(key);}// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5// Convert Set object to an Array object, with Array.fromconst myArr = Array.from(mySet1); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}, 5]// the following will also work if run in an HTML documentmySet1.add(document.body);mySet1.has(document.querySelector("body")); // true// converting between Set and Arrayconst mySet2 = new Set([1, 2, 3, 4]);console.log(mySet2.size); // 4console.log([...mySet2]); // [1, 2, 3, 4]// intersect can be simulated viaconst intersection = new Set([...mySet1].filter((x) => mySet2.has(x)));// difference can be simulated viaconst difference = new Set([...mySet1].filter((x) => !mySet2.has(x)));// Iterate set entries with forEach()mySet2.forEach((value) => {  console.log(value);});// 1// 2// 3// 4

Implementing basic set operations

js
function isSuperset(set, subset) {  for (const elem of subset) {    if (!set.has(elem)) {      return false;    }  }  return true;}function union(setA, setB) {  const _union = new Set(setA);  for (const elem of setB) {    _union.add(elem);  }  return _union;}function intersection(setA, setB) {  const _intersection = new Set();  for (const elem of setB) {    if (setA.has(elem)) {      _intersection.add(elem);    }  }  return _intersection;}function symmetricDifference(setA, setB) {  const _difference = new Set(setA);  for (const elem of setB) {    if (_difference.has(elem)) {      _difference.delete(elem);    } else {      _difference.add(elem);    }  }  return _difference;}function difference(setA, setB) {  const _difference = new Set(setA);  for (const elem of setB) {    _difference.delete(elem);  }  return _difference;}// Examplesconst setA = new Set([1, 2, 3, 4]);const setB = new Set([2, 3]);const setC = new Set([3, 4, 5, 6]);isSuperset(setA, setB); // returns trueunion(setA, setC); // returns Set {1, 2, 3, 4, 5, 6}intersection(setA, setC); // returns Set {3, 4}symmetricDifference(setA, setC); // returns Set {1, 2, 5, 6}difference(setA, setC); // returns Set {1, 2}

Relation to arrays

js
const myArray = ["value1", "value2", "value3"];// Use the regular Set constructor to transform an Array into a Setconst mySet = new Set(myArray);mySet.has("value1"); // returns true// Use the spread syntax to transform a set into an Array.console.log([...mySet]); // Will show you exactly the same Array as myArray

Remove duplicate elements from an array

js
// Use to remove duplicate elements from an arrayconst numbers = [2, 13, 4, 4, 2, 13, 13, 4, 4, 5, 5, 6, 6, 7, 5, 32, 13, 4, 5];console.log([...new Set(numbers)]); // [2, 13, 4, 5, 6, 7, 32]

Relation to strings

js
// Case sensitive (set will contain "F" and "f")new Set("Firefox"); // Set(7) [ "F", "i", "r", "e", "f", "o", "x" ]// Duplicate omission ("f" occurs twice in the string but set will contain only one)new Set("firefox"); // Set(6) [ "f", "i", "r", "e", "o", "x" ]

Use a set to ensure the uniqueness of a list of values

js
const array = Array.from(document.querySelectorAll("[id]")).map((e) => e.id);const set = new Set(array);console.assert(set.size === array.length);

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-set-objects

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp