The first is a more conventional method
Idea:
1. Build a new array storage result
2. Take an element from the original array in theFOR cycle, compare with the array with this element cycle with the result of this element
3. If there is no such element in the result array, it is stored in the 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
Idea:
1. Sort the original array first
2. Check whether the first element in the original array is the same as the last element in the result array. Because it is sorted, the repetitive elements will be in the adjacent position
3. If different, save the element into 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.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 will also have a certain limitations, because the sorting before the return, the last return result of the last return is also sorted. If the order of the array is required not to change the order, then this method cannot be taken.
The third method (recommended)
Idea:
1. Create a new array storage result
2. Create an empty object
3. When theFOR cycle, take out an element and object each time to compare it. If this element is not repeated, it is stored in the result array. To the object established in step 2.
Note: As for how to compare, take a element from the original array and then access this attribute in the object. If you can access the value, it means 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 ());