JavaScript

Unique Array Values

by @admin
10h ago
Apr 28, 2026
Public
Returns a new array with duplicate values removed. The fast version uses a Set for primitives. The deep version supports deduplicating objects by a specific key, making it suitable for deduplicating API results or merged data sets.
JavaScript
// Primitives
const unique = (arr) => [...new Set(arr)];

// Objects — deduplicate by key
const uniqueBy = (arr, key) => {
  const seen = new Set();
  return arr.filter((item) => {
    const k = typeof key === 'function' ? key(item) : item[key];
    return seen.has(k) ? false : seen.add(k);
  });
};

// Usage
console.log(unique([1, 2, 2, 3, 3, 3])); // [1, 2, 3]

const users = [{ id: 1 }, { id: 2 }, { id: 1 }];
console.log(uniqueBy(users, 'id')); // [{ id: 1 }, { id: 2 }]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.