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.
Medium arrays
Arrays containing 40 thousand integers.
Larger arrays
Arrays containing 4 million integers.
Tiny arrays
Arrays containing 4 integers.
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.