Sometimes you encounter this kind of requirement, and you need to delete the duplicate elements in the array and keep only one. The first thing that comes to mind is probably to use two for loops to compare and remove duplicate elements. The code is as follows:
Method 1:
for ( var i = 0; i < len; i ){
for( var j = i 1; j < len; j ){
if( this[i] === this [j] ){
j = i;
}
}
arr.push( this[i] );
}
return arr;
};
If you use method 1 and encounter a lot of data, the performance will be much worse. Then please continue to see the method below.
Method 2:
Method 2 uses sort’s custom callback function, and also uses indexOf, a method that IE6/7/8 does not support. Of course, indexOf can be simulated by yourself, but the bigger problem is that there are differences between the sort method of IE6/7/8 and standard browsers. There are many traps in custom callback functions using the sort method in IE6/7/8. The code of the custom sort callback function above will directly report a "missing number" error in IE6/7/8. The return of the callback function If it is NaN, this error will be reported, because theoretically the sort callback function can only return integers. Even if the problem of return value is ignored, there are still other problems. In the end, there is not too much to worry about. Method 2 does not work in IE6/7/8.
Looked at method 3 from Fool's Wharf, here is his code:
Method 3 uses a temporary object to store the elements of the array. If duplicate array elements are encountered, they will be ignored. However, if you encounter the following array:
If you use method 3 in the above array, 1 and "1" will be mistakenly regarded as duplicate elements and deleted, so method 3 has been slightly modified to solve this bug.
Modified version of method 3:
for( ; i < len; i ){
result = this[i];
if( obj[result] !== result ){
arr.push( result );
obj[result] = result;
}
}
return arr;
};
Then I read the comments at the end of the Fool’s Wharf article. This method is the same as the method provided by Rekey, but this method also has bugs. If you encounter such a 2B array, it will be a disaster:
Using the modified version of method 3 for the above array, the last three elements will not be deleted. However, this kind of array is a bit extreme. If you encounter data with the same string literal and number, you should pre-process it to avoid this. BUG. The method using temporary objects is slightly faster than sort in standard browsers, and the algorithm of the sort method in each browser should also be different.