The first method is the conventional method: Create a new array to store the results. In the for loop, each time an element is retrieved from the original array, indexOf is used to find whether the element exists in the new array, for the second type, read this article in detail.
The first method is more common.
Ideas:
1. Create a new array to store the results
2. In the for loop, an element is extracted from the original array each time, and indexOf is used to find whether the element exists in the new array.
3. If not, it is saved to the result array.
The Code is as follows:
Array. prototype. unique1 = function (){
Var res = [];
For (var I = 0; I <this. length; I ++ ){
If (res. indexOf (this [I]) =-1 ){
Res. push (this [I]);
}
}
Return res;
}
Var arr = [1, 'A', 'A', 'B', 'D', 'E', 'E', 1, 0]
Alert (arr. unique1 ())
On this basis, it can be slightly optimized, but the principle remains unchanged, and the effect is not obvious.
The Code is as follows:
Array. prototype. unique1 = function (){
Var res = [this [0]; // directly store the first element in the original array into the new array.
For (var I = 1; I <this. length; I ++) {// The loop starts from the second element.
If (res. indexOf (this [I]) =-1 ){
Res. push (this [I]);
}
}
Return res;
}
Var arr = [1, 'A', 'A', 'B', 'D', 'E', 'E', 1, 0]
Alert (arr. unique1 ())
The second method is more efficient than the above method.
Ideas:
1. Sort the original array first
2. Check whether the I-th element in the original array is the same as the last element in the result array. Because the elements have been sorted, the repeated elements are in the adjacent positions.
3. If the elements are different, the elements are stored in the result array.
The Code is as follows:
Array. prototype. unique2 = function (){
This. sort (); // sort first
Var res = [this [0];
For (var I = 1; I <this. length; I ++ ){
If (this [I]! = Res [res. length-1]) {
Res. push (this [I]);
}
}
Return res;
}
Var arr = [1, 'A', 'A', 'B', 'D', 'E', 'E', 1, 0]
Alert (arr. unique2 ())