How to remove duplicates from an array in JavaScript
Dealing with duplicate values in JavaScript arrays is a common issue, especially when working with data from APIs or user input where duplicate entries can occur unexpectedly.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve solved this problem countless times in production components like user lists, tag systems, and data aggregation features where clean, unique datasets are essential.
From my extensive expertise, the most efficient and modern solution is to use the ES6 Set
object together with the spread operator.
This method is concise, reliable, and supported across all modern browsers while maintaining excellent performance.
Use Set
with spread syntax to quickly remove duplicates from an array.
const numbers = [1, 2, 2, 3, 3, 4]
const unique = [...new Set(numbers)]
// Result: [1, 2, 3, 4]
The Set
constructor creates a new Set object containing only unique values from the array, automatically removing any duplicates. The spread operator ...
then expands those unique values back into a new array. In this example, [1, 2, 2, 3, 3, 4]
becomes [1, 2, 3, 4]
with all duplicate numbers removed. This method preserves the order of first occurrence, so the first instance of each value is kept while subsequent duplicates are discarded.
Best Practice Note:
This is the same approach we use in CoreUI components to ensure clean and predictable data across our component library.
For extremely large datasets, a filter
with indexOf
may offer more control, but Set
is the go-to method for most cases. For objects, use filter
with custom comparison logic based on specific properties.