Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Possible Duplicate:
Easiest way to find duplicate values in a javascript array

How do I check if an array has duplicate values?

If some elements in the array are the same, then return true. Otherwise, return false.

['hello','goodbye','hey'] //return false because no duplicates exist
['hello','goodbye','hello'] // return true because duplicates exist
share|improve this question

marked as duplicate by Brian Roach, mu is too short, Joseph Silber, Sasha Chedygov, Ben Alpert Sep 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.

    
Here it is: stackoverflow.com/questions/840781/… – Ofer Zelig Sep 11 '11 at 6:06
    
I don't want a list of duplicates removed. I just want to know true or false if a list has duplicates in it. – user847495 Sep 11 '11 at 6:08
    
The accepted answer for the exact same question you asked is your answer. stackoverflow.com/questions/840781/… – Brian Roach Sep 11 '11 at 6:28
    
jsfiddle.net/vol7ron/gfJ28 – vol7ron Sep 11 '11 at 6:42
2  
This question is not a duplicate. Since @user847495 simply wants to check if duplicates exists, the solution is faster/easier than what's needed to find all occurrences of duplicates. For example, you can do this: codr.io/v/bvzxhqm – alden Sep 26 '15 at 16:32
up vote 37 down vote accepted

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)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

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).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

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.

share|improve this answer
2  
About the first example you gave. Isn't the validation exactly the other way around? If your function is named hasDuplicates, then it should check if the set's size actually shrunk during the process of casting it, right? Therefore the boolean operator should be !== and not === – Tim Dau Jul 1 '15 at 13:45
    
pls edit. I can't edit as I'm not changing more than 6 characters. – Tim Dau Jul 3 '15 at 9:32
    
According to MDN IE11 does not the support the constructor used in the first example – adam77 Feb 1 at 19:40

Another approach (also for object/array elements within the array1) could be2:

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also...

1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values

share|improve this answer
1  
Non-showstopper issues worth being aware of: 1) mutates the original array to be sorted; 2) does not differentiate between null, NaN, Infinity, +Infinity, and -Infinity; 3) objects are considered equal if they have the same own-properties, even if they have different prototypes. – Domenic Sep 11 '11 at 6:40
    
@Domenic: yep, should've mentioned it. Edited to circumvent mutation of original array. – KooiInc Sep 11 '11 at 6:45
    
@Domenic: corrected for null/NaN/[+/-]Infinity, see edits. – KooiInc Sep 11 '11 at 6:53
    
@Domenic: Issue 3) is actually not a problem for me, because it is exactly what I want. I don't care about the prototype, just the values. – awe Nov 19 '15 at 5:59

Well I did a bit of searching around the internet for you and I found this handy link.

Easiest way to find duplicate values in a javascript array

You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.