I need to check a JavaScript array to see if there are any duplicate values. What's the easiest way to do this? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated.
I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way. Any ideas? Thanks!
Using "includes" to test if the element already exists.
I have just figured out a simple way to achieve this using an Array filter
Just to add some theory to the above.
Finding duplicates has a lower bound of O(n*log(n) in the comparison model. SO theoretically, you cannot do any better than first sorting then going through the list sequentially removing any duplicates you find.
If you want to find the duplicates in linear (O(n)) expected time, you could hash each element of the list; if there is a collision, remove/label it as a duplicate, and continue.
To solve the above in O(n) time complexity (without sorting).
This function avoids the sorting step and uses the reduce() method to push duplicates to a new array if it doesn't already exist in it.
You can add this function, or tweak it and add it to Javascript's Array prototype: