Your Course Progress

Topics
0 / 0
0.00%
Practice Tests
0 / 0
0.00%
Tests
0 / 0
0.00%
Assignments
0 / 0
0.00%
Content
0 / 0
0.00%
% Completed

JavaScript Sets

Table of Contents

A Set in JavaScript is a collection of unique values. Unlike arrays, a Set automatically removes duplicate entries. It can hold any type of value—primitive or object references.

JavaScript Set and Its Methods:

A Set in JavaScript is a collection of unique values. Unlike arrays, a Set automatically removes duplicate entries. It can hold any type of value—primitive or object references.

  • Unique values: A Set ensures that all elements are unique.
  • Iterable: Sets are iterable, meaning you can loop over their values.
  • No duplicates: Any attempt to add duplicate values is ignored.
  • Unordered: Elements in a Set are not indexed and do not follow a specific order.
let mySet = new Set([1, 2, 3, 4, 4, 5]);

console.log(mySet); // Output: Set {1, 2, 3, 4, 5}

In this example, the duplicate 4 is removed automatically.

You can create a Set using the Set constructor, either with or without an iterable (like an array) as its input.

let emptySet = new Set();
let setFromArray = new Set([10, 20, 30, 40]);

console.log(setFromArray); // Output: Set {10, 20, 30, 40}

JavaScript provides several methods for working with Sets, allowing you to manipulate and inspect the collection.

The add() method adds a new element to the Set. If the element already exists, it is not added again.

Example:

let numbers = new Set();
numbers.add(1);
numbers.add(2);
numbers.add(2); // Duplicate, won't be added

console.log(numbers); // Output: Set {1, 2}

The delete() method removes a specific element from the Set and returns true if the element was successfully removed.

Example:

let colors = new Set(['Red', 'Green', 'Blue']);
colors.delete('Green');

console.log(colors); // Output: Set { 'Red', 'Blue' }

The has() method checks if a particular element exists in the Set. It returns true if the element is found, otherwise false.

Example:

let cities = new Set(['New York', 'London']);

console.log(cities.has('London')); // Output: true
console.log(cities.has('Paris'));  // Output: false

The clear() method removes all elements from the Set, making it empty.

Example:

let fruits = new Set(['Apple', 'Banana']);
fruits.clear();

console.log(fruits); // Output: Set {}

The size property returns the number of elements in the Set.

Example:

let fruits = new Set(['Apple', 'Banana', 'Mango']);

console.log(fruits.size); // Output: 3

Sets can be iterated over in various ways, thanks to the iterable nature of this data structure.

The forEach() method executes a provided function once for each value in the Set.

Example:

let languages = new Set(['JavaScript', 'Python', 'C++']);
languages.forEach(lang => console.log(lang));

// Output:
// JavaScript
// Python
// C++

The values() method returns a new iterator object containing all the values in the Set. It’s essentially the same as the keys() method, as Sets do not have keys.

Example:

let numbers = new Set([1, 2, 3]);
let valuesIterator = numbers.values();

console.log(valuesIterator.next().value); // Output: 1

The entries() method returns an iterator object with key-value pairs, where both the key and the value are the same for each entry.

Example:

let set = new Set(['a', 'b', 'c']);

for (let entry of set.entries()) {
  console.log(entry);
}

// Output:
// ['a', 'a']
// ['b', 'b']
// ['c', 'c']

The keys() method returns the same iterator as values(). Since Sets don’t have keys, the method returns the values of the Set.

Example:

let set = new Set([100, 200, 300]);

for (let key of set.keys()) {
  console.log(key); // Output: 100, 200, 300
}

While JavaScript’s Set object doesn’t include methods like union, intersection, or difference by default, you can implement them manually using the Set’s methods.

To create a union of two sets (all unique elements from both sets), use the add() method.

Example:

let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);

let unionSet = new Set([...setA, ...setB]);

console.log(unionSet); // Output: Set {1, 2, 3, 4, 5}

To create an intersection of two sets (common elements in both sets), use the has() method.

Example:

let setA = new Set([1, 2, 3]);
let setB = new Set([2, 3, 4]);

let intersection = new Set([...setA].filter(x => setB.has(x)));

console.log(intersection); // Output: Set {2, 3}

To find the difference of two sets (elements in set A but not in set B), use the has() method.

Example:

let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);

let difference = new Set([...setA].filter(x => !setB.has(x)));

console.log(difference); // Output: Set {1, 2}

A WeakSet is a special type of Set that only holds objects and does not prevent them from being garbage collected. WeakSets have the following differences from Sets:

  • Only accepts objects (not primitive values).
  • WeakSet elements are not enumerable and cannot be iterated.
  • Methods include add(), delete(), and has(), but not size, clear(), or iteration methods.

Example:

let ws = new WeakSet();
let obj = {};
ws.add(obj);

console.log(ws.has(obj)); // Output: true
  • Sets in JavaScript are an efficient way to store unique values.
  • They offer several useful methods to manipulate and retrieve data, making them an excellent tool when you need collections with no duplicates.
  • Additionally, you can manually implement set operations such as union, intersection, and difference.

Discussion