Javascript Fundamentals · Array Methods

Remove duplicates with a Set

Set dedupe

Remove duplicates with a Set

You have a list of tags or IDs where the same value shows up again and again, and you want each one only once. A Set is a collection of unique values. Adding a value it already holds is a no-op, and a Set remembers insertion order. That makes it the shortest way to dedupe an array: build a Set from the array, then spread it back into a new array.

Picture a guest list typed twice by mistake: a Set keeps the first appearance of each name and silently drops the repeats.

const values = ['a', 'b', 'a', 'c', 'b'];

[...new Set(values)]; // ['a', 'b', 'c']

new Set(values) walks the input and keeps one of each value, using SameValueZero equality — the rule that also makes NaN equal to itself. Spreading the Set back turns it into a normal array in first-seen order. The original array is never changed; you get a fresh, duplicate-free array.

One caveat: Set membership is by value for primitives but by reference for objects, so two objects that look identical are still two different entries. Deduping records by a field needs a Map keyed by that field instead.

Export uniqueValues from index.js. Called with an array, it returns a new array with the duplicates removed, keeping first-seen order, using a Set.

Challenge

You have a list where the same value appears several times, and you want each distinct value once, in the order you first saw it. Export uniqueValues from index.js.

It takes an array and returns a new array holding each distinct value once, in the order it first appeared. Build a Set from the array to drop repeats, then spread it back into an array. The original array must not be changed.

index.js
export function uniqueValues(list) {
  return list;
}

export function render(mount) {
  const values = ['a', 'b', 'a', 'c', 'b'];

  mount.innerHTML = `
    <p>Values: ${values.join(', ')}</p>
    <p>Unique: ${uniqueValues(values).join(', ')}</p>
  `;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.