114
votes

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

Notice I don't care about finding the duplication, only want Boolean result whether arrays contains duplications.

7
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
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/bvzxhqmalden
using underscore ,simple technique var test=['hello','goodbye','hello'] ; if ( test.length != _.unique(test).length ) { // some code }Sai Ram
Not a duplicate of the marked question. Please pay attention before marking questions as such.John Weisz

7 Answers

262
votes

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 in to see if that value has been spotted already; if so, we bail out of the loop and return true.


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 in, instead getting an O(n) lookup time of indexOf.

6
votes

You could use SET to remove duplicates and compare, If you copy the array into a set it will remove any duplicates. Then simply compare the length of the array to the size of the set.

function hasDuplicates(a) {

  const noDups = new Set(a);

  return a.length !== noDups.size;
}
5
votes

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.
2edit: function can now be used for simple check or to return an array of duplicate values

2
votes

You can take benefit of indexOf and lastIndexOf. if both indexes are not same, you have duplicate.

function containsDuplicates(a) {
  for (let i = 0; i < a.length; i++) {
    if (a.indexOf(a[i]) !== a.lastIndexOf(a[i])) {
      return true
    }
  }
  return false
}
1
votes

If you are dealing with simple values, you can use array.some() and indexOf()

for example let's say vals is ["b", "a", "a", "c"]

const allUnique = !vals.some((v, i) => vals.indexOf(v) < i);

some() will return true if any expression returns true. Here we'll iterate values (from the index 0) and call the indexOf() that will return the index of the first occurrence of given item (or -1 if not in the array). If its id is smaller that the current one, there must be at least one same value before it. thus iteration 3 will return true as "a" (at index 2) is first found at index 1.

-2
votes
function hasAllUniqueChars( s ){ 
    for(let c=0; c<s.length; c++){
        for(let d=c+1; d<s.length; d++){
            if((s[c]==s[d])){
                return false;
            }
        }
    }
    return true;
}
-3
votes

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.