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!
I did not like most answers.
Why? Too complicated, too much code, inefficient code and many do not answer the question, which is to find the duplicates (and not to give an array without the duplicates).
Next function returns all duplicates:
Because most of the time it is of no use to return ALL duplicates, but just to tell which duplicate values exist. In that case you return an array with unique duplicates ;-)
Maybe somebody else thinks the same.
When all you need is to check that there are no duplicates as asked in this question you can use the
every()
method:Note that
every()
doesn't work for IE 8 and below.I use
lastIndexOf()
because it might be more efficient thanindexOf()
if function callbacks made byevery()
are made in the index order, but that's not proven.In CoffeeScript I'm using this:
I prefer the function way of doing this.
This uses underscore, but Array has a
reduce
function, tooUPDATED: The following uses an optimized combined strategy. It optimizes primitive lookups to benefit from hash O(1) lookup time (running
unique
on an array of primitives is O(n)). Object lookups are optimized by tagging objects with a unique id while iterating through so so identifying duplicate objects is also O(1) per item and O(n) for the whole list. The only exception is items that are frozen, but those are rare and a fallback is provided using an array and indexOf.If you have ES6 Collections available, then there is a much simpler and significantly faster version. (shim for IE9+ and other browsers here: https://github.com/Benvie/ES6-Harmony-Collections-Shim)
This should get you what you want, Just the duplicates.