Home

How to remove duplicates from a javascript array

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
Click here to run the tests yourself

Medium arrays

Arrays containing 40 thousand integers.

Performance for arrays of length 40
Click here to run the tests yourself

Larger arrays

Arrays containing 4 million integers.

Performance for arrays of length 4 million
Click here to run the tests yourself

Tiny arrays

Arrays containing 4 integers.

Performance for arrays of length 4
Click here to run the tests yourself

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.
  • SurpirsinglySpread 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.