How to find unique values in an array?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Arrays #JS Basics

Brief Answer

There are several ways to find unique values in JavaScript array:

  1. Set — simplest and fastest way 🆕
  2. filter with indexOf — classic way 📚
  3. reduce — functional approach 🔧
const arr = [1, 2, 2, 3, 3, 4];
 
// Set — most common way
const unique1 = [...new Set(arr)]; // [1, 2, 3, 4]
 
// filter with indexOf
const unique2 = arr.filter((item, index) => arr.indexOf(item) === index); // [1, 2, 3, 4]
 
// Both work, but Set is faster!

Full Answer

Finding unique values is like sorting socks in a drawer, keeping one of each color! 🧦✨

Set (Most Common Way)

Simplest and fastest way — use [Set]:

const colors = ['red', 'blue', 'red', 'green', 'blue'];
 
// Create Set (unique values) and back to array
const unique = [...new Set(colors)];
console.log(unique); // ['red', 'blue', 'green']
 
// Works with any values
const mixed = [1, '1', 1, true, true, false];
console.log([...new Set(mixed)]); // [1, '1', true, false]

filter with indexOf (Classic Way)

Check if element is first in array:

const numbers = [1, 2, 2, 3, 3, 4];
 
const unique = numbers.filter((item, index) => {
  return numbers.indexOf(item) === index;
});
 
console.log(unique); // [1, 2, 3, 4]
 
// How it works:
// For 1: indexOf(1) = 0, index = 0 → 0 === 0 ✅
// For 2: indexOf(2) = 1, index = 1 → 1 === 1 ✅
// For 2: indexOf(2) = 1, index = 2 → 1 !== 2 ❌ (skip)

reduce (Functional Way)

Accumulate unique values:

const arr = [1, 2, 2, 3, 3, 4];
 
const unique = arr.reduce((acc, current) => {
  if (!acc.includes(current)) {
    acc.push(current);
  }
  return acc;
}, []);
 
console.log(unique); // [1, 2, 3, 4]

When to Use What

Set — for most cases

// ✅ Simple and fast
const arr = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(arr)];

filter + indexOf — for compatibility

// ✅ Works everywhere, even old browsers
const arr = [1, 2, 2, 3, 3, 4];
const unique = arr.filter((item, index) => arr.indexOf(item) === index);

reduce — when complex logic needed

// ✅ When you need special accumulation logic
const arr = [1, 2, 2, 3, 3, 4];
const unique = arr.reduce((acc, current) => {
  // Custom logic...
  return acc;
}, []);

Special Cases

With objects

// ❌ Set won't help with objects
const arr = [{id: 1}, {id: 1}, {id: 2}];
const unique = [...new Set(arr)]; // Doesn't work!
 
// ✅ Need custom logic
const uniqueObjects = arr.filter((item, index, self) => 
  index === self.findIndex(obj => obj.id === item.id)
);

With null/undefined

// ✅ Works fine
const arr = [1, null, undefined, 1, null];
console.log([...new Set(arr)]); // [1, null, undefined]

Common Mistakes

Thinking Set works with nested objects

// ❌ Mistake
const arr = [[1, 2], [1, 2], [3, 4]];
const unique = [...new Set(arr)]; // Won't remove duplicates!
 
// ✅ Correct — convert to strings
const uniqueArrays = [...new Set(arr.map(JSON.stringify))].map(JSON.parse);

Using inefficient ways

// ❌ Slow for large arrays
const arr = [/* large array */];
arr.filter(item => arr.indexOf(item) === arr.lastIndexOf(item)); // Very slow!
 
// ✅ Fast
const unique = [...new Set(arr)];

Simple Rules

  1. Set — fastest and simplest way 🆕
  2. filter + indexOf — classic but slow 📚
  3. reduce — flexible but complex 🔧
  4. Set with objects — doesn’t work as expected ⚠️
  5. Performance — Set is faster for large arrays ⚡

Knowing different ways to find unique values helps choose the right tool! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪