JavaScript Sets
A `Set` is a built-in collection that stores unique values of any type — no duplicates are allowed. Sets remember insertion order and are great for filtering duplicate data.
You create a Set with `new Set()`, optionally passing an iterable like an array, and manage it with `add()`, `delete()`, and `has()`.
Creating and using Sets
`new Set([1, 2, 2, 3])` automatically removes the duplicate, resulting in a Set containing 1, 2, 3.
Set methods
`add(value)` inserts, `delete(value)` removes, `has(value)` checks membership, and `size` gives the count of elements.
let nums = new Set([1, 2, 2, 3, 3]);
console.log(nums);
console.log(nums.size);Set(3) { 1, 2, 3 }
3Duplicates are automatically removed when creating the Set.
let arr = [1, 1, 2, 2, 3];
let unique = [...new Set(arr)];
console.log(unique);[1, 2, 3]Converting to a Set and back to an array is a common way to deduplicate.
Key points
- A Set stores only unique values.
- `add()`, `delete()`, `has()` manage Set contents.
- `size` gives the number of elements (not `length`).
- Sets preserve insertion order.
