Skip to content
GreenSnippets

Remove duplicates from an array

Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.

JavaScript
function uniqueBy(array, getKey = (item) => item) {
  const seen = new Set();
  return array.filter((item) => {
    const key = getKey(item);
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

Example / expected output

Output
uniqueBy([{ id: 1 }, { id: 2 }, { id: 1 }], (u) => u.id) // [{ id: 1 }, { id: 2 }]

How it works

For primitives [...new Set(array)] is enough. For objects, pass a function that returns the identity of each item. The first occurrence wins and the original order is preserved.