There are several ways to find unique values in JavaScript array:
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!Finding unique values is like sorting socks in a drawer, keeping one of each color! 🧦✨
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]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)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]// ✅ Simple and fast
const arr = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(arr)];// ✅ Works everywhere, even old browsers
const arr = [1, 2, 2, 3, 3, 4];
const unique = arr.filter((item, index) => arr.indexOf(item) === index);// ✅ When you need special accumulation logic
const arr = [1, 2, 2, 3, 3, 4];
const unique = arr.reduce((acc, current) => {
// Custom logic...
return acc;
}, []);// ❌ 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)
);// ✅ Works fine
const arr = [1, null, undefined, 1, null];
console.log([...new Set(arr)]); // [1, null, undefined]// ❌ 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);// ❌ 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)];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 💪