The first is a more conventional approach.
Ideas:
1. Build a new array to store the results
Each time in the 2.for loop, an element is fetched from the original array, and the element loop is compared with the result array.
3. If the element is not in the resulting array, it is stored in the result array
Copy Code code as follows:
Array.prototype.unique1 = function () {
var res = [This[0]];
for (var i = 1; i < this.length; i++) {
var repeat = false;
for (var j = 0; J < Res.length; J + +) {
if (this[i] = = Res[j]) {
repeat = true;
Break
}
}
if (!repeat) {
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 ());
The second method also has some limitations, because it is sorted before the heavy weight, so the final return of the weight result is also sorted. This method is not available if the order of the array is not changed to heavy.
Third method (recommended)
Ideas:
1. Create a new array to store the results
2. Create an empty object
3.for loop, each fetch an element to compare with the object, if the element does not repeat, then put it into the result array, and the content of this element as an attribute of the object, and assign a value of 1, into the object established in step 2nd.
Description: As to how to compare, it is every time from the original array to take out an element, and then access to this property in the object, if you can access the value, the description is repeated.
Copy Code code as follows:
Array.prototype.unique3 = function () {
var res = [];
var json = {};
for (var i = 0; i < this.length; i++) {
if (!json[this[i]]) {
Res.push (This[i]);
Json[this[i]] = 1;
}
}
return res;
}
var arr = [112,112, 34, ' Hello ', 112,112, 34, ' hello ', ' str ', ' str1 '];
Alert (Arr.unique3 ());