Ever wondered about the different ways you can remove duplicates from a JavaScript array?
This short article shows a few methods and compares how they perform when provided with arrays of different sizes.
Small arrays
Arrays containing 25 integers.
![Performance for arrays of length 25](/media/small-array.png)
Medium arrays
Arrays containing 40 thousand integers.
![Performance for arrays of length 40](/media/medium-array-1.png)
Larger arrays
Arrays containing 4 million integers.
![Performance for arrays of length 4 million](/media/larger-array-1.png)
Tiny arrays
Arrays containing 4 integers.
![Performance for arrays of length 4](/media/tiny-array.png)
Conclusion
- Performance wise the clear winner is
Regular for loop with object key
. - In terms of conciseness and readability,
Spread set
is my favorite. - Not suprisingly
Filter with indexOf
performs well with tiny arrays, where it’s O(n²) is not an issue. - Surpirsingly
Spread set
was 76% slower for larger arrays, even though it was the second best. I would have thought it would be the most optimized solution.