Understanding and Using JavaScript Set for Unique Collections

Introduced in ECMAScript 2015 (ES6), the Set object is a collection of unique values. Unlike arrays, elements in a Set are stored without indices and cannot be accessed by position. Each value may occur only once within a Set, making it ideal for scenarios requiring uniqueness and automatic deduplication.

Key characteristics and methods include:

  • Uniqueness: Duplicate values are automatically ignored.
  • No index-based access: Elements must be iterated or checked via methods.
  • add(value): Adds a new element to the set.
  • delete(value): Removes a specific element.
  • has(value): Returns true if the value exists.
  • size: Property that returns the number of elemants.
  • clear(): Removes all elements from the set.

Basic Usage Example

const uniqueCollection = new Set();
uniqueCollection.add({ name: "zooey", age: 19 });
uniqueCollection.add(20);
uniqueCollection.add(3);
uniqueCollection.add(3); // Ignored due to duplication

console.log(uniqueCollection.has(20)); // true
console.log(uniqueCollection.size);    // 3

uniqueCollection.delete(20);
console.log([...uniqueCollection]);   // [{ name: "zooey", age: 19 }, 3]

Common Set Operations

Using Set enables efficient array deduplication and set-theoretic operations like union, intersection, and difference.

const listA = [1, 3, 4, 4, 5, 7, 7, 9, 10];
const listB = [2, 4, 6, 8, 8, 10];

const setA = new Set(listA);
const setB = new Set(listB);

// Deduplication
console.log([...setA]); // [1, 3, 4, 5, 7, 9, 10]

// Intersection (elements in both sets)
const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log([...intersection]); // [4, 10]

// Union (all unique elements from both sets)
const union = new Set([...setA, ...setB]);
console.log([...union]); // [1, 3, 4, 5, 7, 9, 10, 2, 6, 8]

// Difference (elements in setA but not in setB)
const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log([...difference]); // [1, 3, 5, 7, 9]

Iteration Methods

Set provides iterable methods that behave identically since keys and values are the same:

const people = new Set([
  { name: "zooey", age: 18 },
  { name: "anan", age: 19 },
  { name: "bobo", age: 20 }
]);

// entries() returns [value, value] pairs
for (const [key, value] of people.entries()) {
  console.log(key === value); // true for each entry
}

// keys() and values() are equivalent in Set
for (const person of people.keys()) {
  console.log(person.name); // "zooey", "anan", "bobo"
}

for (const person of people.values()) {
  console.log(person.age); // 18, 19, 20
}

Tags: javascript ES6 Set

Posted on Wed, 14 Oct 2026 16:46:18 +0000 by n00854180t