views:

311

answers:

3
var arr = ['test0','test2','test0'];

Like the above,there are two identical entries with value "test0",how to check it most efficiently?

+1  A: 

Loop stops when found first duplicate:

function has_duplicates(arr) {

    var x = {}, len = arr.length;
    for (var i = 0; i < len; i++) {
        if (x[arr[i]]) {
             return true;
        }
        x[arr[i]] = true;
    }
    return false;

}

Edit (fix 'toString' issue):

function has_duplicates(arr) {

    var x = {}, len = arr.length;
    for (var i = 0; i < len; i++) {
        if (x[arr[i]] === true) {
             return true;
        }
        x[arr[i]] = true;
    }
    return false;

}

this will correct for case has_duplicates(['toString']); etc..

Anatoliy
Careful: using Object as a map has difficulties. Keys may only be strings, and names that are members of Object will confuse it. eg. `has_duplicates(['toString'])` is `true`.
bobince
Thanks for this. Fixed.
Anatoliy
As bobince says. **All keys will be converted to strings**. So the above would give a false positive with the following: `[ {a: 1}, {b: 2} ]` since both members of the array will become "[object Object]" when being stored as keys in `x`.
Tim Down
Gah, I hate SO on this. I downvoted and commented on your original answer and now cannot remove it.
Tim Down
In original question array contains only strings. You are correct -- my solition is not working for all possible types, but there is other task.
Anatoliy
+6  A: 

If you sort the array, the duplicates are next to each other so that they are easy to find:

arr.sort();
var last = arr[0];
for (var i=1; i<arr.length; i++) {
   if (arr[i] == last) alert('Duplicate : '+last);
   last = arr[i];
}
Guffa
... assuming your values are all strings or numbers. Sorting will do no good for an arbitrary array of objects.
Tim Down
If it's an arbitrary array of objects then it's also difficult to check if they're identical.
Skilldrick
@Tim: Good point. However, if the can't be sorted, they can hardly be compared to look for duplicates...
Guffa
You can check whether any array values are identical using the identity operator (`===`). Sorting an array of objects to bring duplicates to the start requires knowledge of the types of objects being compared in order to decide how to compare them.
Tim Down
+2  A: 

This will do the job on any array and is probably about as optimized as possible for handling the general case (finding a duplicate in any possible array). For more specific cases (e.g. arrays containing only strings) you could do better than this.

function hasDuplicate(arr) {
    var i = arr.length, j, val;

    while (i--) {
     val = arr[i];
     j = i;
     while (j--) {
      if (arr[j] === val) {
       return true;
      }
     }
    }
    return false;
}
Tim Down