Removing duplicates from an array is one of the most common JavaScript operations. The cleanest modern approach uses the Set object, but filter and reduce patterns offer more control for complex deduplication scenarios.
Method 1: Using Set (Simplest)
const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(arr)];
// Result: [1, 2, 3, 4, 5]
Set only stores unique values. Spreading it back into an array with [...new Set(arr)] is the most concise and performant approach for primitive values (numbers, strings, booleans). Time complexity: O(n).
Method 2: Using filter and indexOf
const unique = arr.filter((item, index) => arr.indexOf(item) === index);
This keeps only the first occurrence of each value. O(n²) time complexity — slower than Set for large arrays, but readable and useful when you need index information.
Method 3: Deduplicate Array of Objects by Property
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice' } // duplicate
];
const unique = [...new Map(users.map(u => [u.id, u])).values()];
// Result: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
Remove Duplicate Lines from Text Online
For removing duplicate text lines (not JavaScript arrays), Format Pilot’s text utilities include a Remove Duplicates function — paste any list, click Remove Duplicates, and copy the unique lines.
Frequently Asked Questions
Does Set preserve order when removing duplicates?
Yes. JavaScript’s Set preserves insertion order. When you convert an array to a Set and back, the elements appear in the same order they first appeared in the original array, with duplicates removed.