Creating Sets
A Set is a collection of unique values. You can create a Set in multiple ways depending on your needs.
Using the Set Constructor
The most common way to create a Set is by using the Set
constructor, which can take an iterable (like an array or string) as an argument:
// Create a Set from an array
const numbers = new Set([1, 2, 3, 4]);
console.log(numbers); // Set { 1, 2, 3, 4 }
// Create a Set from a string (duplicates removed)
const chars = new Set("hello");
console.log(chars); // Set { 'h', 'e', 'l', 'o' }
Creating an Empty Set
You can start with an empty Set and add elements later using the .add()
method:
const emptySet = new Set();
emptySet.add(10);
emptySet.add(20);
emptySet.add(10); // Duplicate, will be ignored
console.log(emptySet); // Set { 10, 20 }
Removing Duplicates from an Array
Sets are often used to filter duplicates from arrays:
const nums = [1, 2, 2, 3, 4, 4, 5];
const uniqueNums = new Set(nums);
console.log(uniqueNums); // Set { 1, 2, 3, 4, 5 }
// Convert back to an array
const uniqueArray = [...uniqueNums];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
Using Arrays or Iterables
Since the Set
constructor accepts any iterable:
const arr = ["apple", "banana", "apple", "orange"];
const fruitSet = new Set(arr);
console.log(fruitSet); // Set { 'apple', 'banana', 'orange' }
Characteristics of Sets
- Uniqueness: Automatically removes duplicates.
- Any Type: Can store numbers, strings, booleans, objects, arrays, functions, etc.
- Insertion Order: Maintains the order in which values are added.
- Size Property:
.size
gives the number of elements in the Set. - Iterability: Supports looping through
for...of
,forEach
, or spreading into an array.
Example
const mixedSet = new Set();
mixedSet.add(1);
mixedSet.add("hello");
mixedSet.add({ name: "Alice" });
mixedSet.add(1); // Duplicate ignored
console.log(mixedSet.size); // 3
console.log([...mixedSet]); // [1, 'hello', { name: 'Alice' }]