The first is a more conventional approach.
Ideas:
1. Build a new array to store the results
In the 2.for loop, every time you take an element out of the original array, you use IndexOf to find out whether the element is in the new array.
3. If not, save in the result array
Copy Code code 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 ())
This foundation can be slightly optimized, but the principle is not changed, the effect is not obvious
Copy Code code as follows:
Array.prototype.unique1 = function () {
var res = [this[0]];//directly to the first element in the original array into the new array being built
for (var i = 1; i < this.length i++) {//loop starts with 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 that the first element in the original array is the same as the last element in the result array, because it is already sorted, so the repeating element is in the adjacent position
3. If it is not the same, the element is stored in the result array
Copy Code code 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 ())