Looking at the source code of YUI from time to time, you will always gain something.
1. Source code in YUI'
var toObject = function(a) {
var o = {};
for (var i=0, j=a.length; io[a[i]] = true;
}
return o;
};
var keys = function(o) {
var a=[], i;
for (i in o) {
if (o.hasOwnProperty(i)) { // here , the YUI source code is lang.hasOwnProperty(o, i)
a.push(i);
}
}
return a;
};
var uniq = function( a) {
return keys(toObject(a));
};
Note: For the convenience of writing, I have omitted the class name before each method. You can check YUI by yourself Source code, both 2.7.0b and 2.8.0r4 are available (this part of the code is the same).
2. The idea of this method
1. First generate an object with the value of the target array as the key . This step is the most important: because the key cannot be repeated in an object, this cleverly excludes duplicate values;
2. Traverse the generated object, take out these keys and put them in In an array, OK, you’re done! (Easy, just two steps)
3. Characteristics of this method
1. For this method, no matter how many items there are in the array, It will only be traversed twice, and the performance advantage is obvious (think about my previous practice: comparing array items one by one, the performance difference can be imagined).
2. After my Test, this method is only applicable to one-dimensional arrays whose array items are strings and numbers (I think it is too unreliable to exclude duplicates in multi-dimensional arrays!).
Other methods You can refer to the previous article.