The Array type does not provide duplicate methods. If you want to kill duplicate elements in an Array, you have to do it yourself:

 1 function unique(arr) {
 2     var result = [], isRepeated;
 3     for (var i = 0, len = arr.length; i < len; i++) {
 4         isRepeated = false;
 5         for (var j = 0, len = result.length; j < len; j++) {
 6             if (arr[i] == result[j]) {   
 7                 isRepeated = true;
 8                 break;
 9             }
10         }
11         if (!isRepeated) {
12             result.push(arr[i]);
13         }
14     }
15     return result;
16 }
Copy the code

 

The idea is to move one array element at a time into another array, checking for duplicates and throwing them away. As you can see from nested loops, this approach is extremely inefficient. We can use the structure of a HashTable to record existing elements, thus avoiding the inner loop. As it happens, implementing hashTable in Javascript is extremely simple, with improvements like the following:

 

function unique(arr) { var result = [], hash = {}; for (var i = 0, elem; (elem = arr[i]) ! = null; i++) { if (! hash[elem]) { result.push(elem); hash[elem] = true; } } return result; //http://www.cnblogs.com/sosoft/ }Copy the code

Methods and examples of use: hovertree.com/h/bjaf/ovjl…