Several methods of the array de-weight in JS
1. Iterate through the array, compare each, compare to the same to delete the following
function Unique (arr) {
for (Var i=0;i<arr.length;i++) {
for (Var j=i+1;j<arr.length;j++) {
if (arr = = Arr[j]) {
&NBSP ; Arr.splice (j,1);
j--;
&NBSP;&NBSP;&NBSP,}
&NBSP;&NBSP;&NBSP,}
& nbsp; ,}
ret Urn Arr.sort ();
}
2. Iterate through the array, compare each one, compare to the same, remove it, and put it in a new array.
function Unique (arr) {
var result=[],isrepeated;
for (Var i=0;i<arr.length;i++) {
Isrepeated=false;
for (Var j=0;j<result.length;j++) {
if (arr = = Result[j]) {
Isresulted=true;
Break
}
}
if (!isrepeated) {
Result.push (arr);
}
}
return result;
}
3. First order, the preceding paragraph and latter comparison, remove the same item
function Unique (arr) {
var temp=[];
This.sort ();
for (Var i=0;i<arr.length;i++) {
if (arr = = Arr[i+1]) {
Continue
}
Temp[temp.length]=arr;
}
return temp;
}
4. Use a Hashtable structure to record existing elements so that the inner loop can be avoided. It happens that the implementation of Hashtable in JavaScript is extremely simple
function Unique (arr) {
var result=[],hash={};
for (var I=0,elem; (elem = arr)! = null;i++) {
if (!hash[elem]) {
Result.push (Elem);
Hash[elem] = true;
}
}
return result;
}
Several methods of the array de-weight in JS