# Set

> The `Set` JS object is a collection of unique values of any type.

## How do I remove duplicates from an array with Set in JavaScript?

The object that holds a collection of unique values of any type, whether they are primitives or objects. Values in a `Set` object are automatically checked for uniqueness, meaning no duplicate values are allowed.

- Topic: Set
- Type: object
- Browser support: Chrome 38+, Chrome Android 38+, Edge 12+, Firefox 13+, Firefox Android 14+, Safari 8+, Safari iOS 8+

## Example

Wrong:

```js
const unique = new Set(tags);
save(JSON.stringify(unique));
```

Right:

```js
const unique = [...new Set(tags)];
save(JSON.stringify(unique));
```

A `Set` serializes to '{}', so spread it into an array first to keep the values.

## Common mistakes

- `new Set([{ id: 1 }, { id: 1 }])` keeps both objects.
- Reading `set.length` and getting `undefined`.

## Key points

- Arrays of objects are not deduplicated with `new Set()`, which compares by reference.
- The code reads `set.size`, not `set.length`.
- Sets are converted to arrays before `JSON.stringify()`, which turns a `Set` into '{}'.

## Interview questions

### How does `Set` compare values?

It uses SameValueZero: like `===`, but `NaN` equals `NaN`. Objects are equal only when they are the same reference.

### Is `Set` faster than an array for lookups?

Usually yes for large collections. `set.has()` does not scan every element, while `array.includes()` does.

### Does `Set` keep insertion order?

Yes. Iteration follows the order in which values were first added.

## Related cards

- [Set.has()](https://wonderium.dev/js/set-has.md)
- [.add()](https://wonderium.dev/js/set-add.md)
- [Map](https://wonderium.dev/js/map.md)
- [WeakSet](https://wonderium.dev/js/weak-set.md)
- [Hash Table](https://wonderium.dev/algorithms/hash-table.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/set
- Last updated: 2026-11-25
