12
7
|
How do I check if an array has duplicate values?
If more than 1 element of the same exist, then return true. Otherwise, return false.
| ||||||||||||||||||||
marked as duplicate by Brian Roach, mu is too short, Joseph Silber, Sasha Chedygov, Ben AlpertSep 11 '11 at 6:39
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
| |||||||||||||||||||||
| |||||||||||||||||||||
26
|
If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):
If you only need string values in the array, the following will work:
We use a "hash table"
valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using Object.prototype.hasOwnProperty.call to see if that value has been spotted already; if so, we bail out of the loop and return true. (We don't use valuesSoFar.hasOwnProperty directly because that would break if the array contained "hasOwnProperty" as a string.)
If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).
The difference is simply that we use an array instead of a hash table for
valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of hasOwnProperty, instead getting an O(n) lookup time of indexOf. |