1. Iterate through the original array and the new array. New an array that holds the unique elements that have been traversed.
function Uniquearr (list) {
var newarr= [list[0]];
for (Var i=1;i<list.length;i++) {
var isrepeat = false;
for (Var j=0;j<newarr.length;j++) {
if (list[i] = = Newarr[j]) {
isrepeat= true;
Break
}
}
if (!isrepeat) {
Newarr.push (List[i]);
}
}
return NEWARR;
}
var arr=[' A ', ' B ', ' C ', ' A ', ' B '];
Uniquearr (arr); Output:["A", "B", "C"]
2, by first sorting, and then compared with the adjacent elements to the weight (after sorting the same element will be adjacent)
function Uniquearr (list) {
List.sort ();//Sort an array
var newarr= [];
for (Var i=1;i<list.length;i++) {
if (list[i]!=list[i+1]) Newarr.push (List[i]);
}
return NEWARR;
}
var arr=[' A ', ' B ', ' C ', ' A ', ' B '];
Uniquearr (arr); Output:["A", "B", "C"]
3, create a new object to store, and then iterate through the array, to determine whether the object exists this value (Obj[i])
function Uniquearr (list) {
var obj= {},newarr=[list[0]];
Obj[list[0]]=true;
for (Var i=1;i<list.length;i++) {
if (!obj[list[i]]) {
Obj[list[i]]=true;
Newarr.push (List[i]);
}
}
return NEWARR;
}
var arr=[' A ', ' B ', ' C ', ' A ', ' B '];
Uniquearr (arr); Output:["A", "B", "C"]
4, judge by IndexOf (create a new data to hold the unique element, traverse the original array to judge (Newarr.indexof (Oldarr[i]) ==-1))
function Uniquearr (list) {
var newarr=[list[0]];
for (Var i=1;i<list.length;i++) {
if (Newarr.indexof (List[i]) ==-1) {
Newarr.push (List[i]);
}
}
return NEWARR;
}
var arr=[' A ', ' B ', ' C ', ' A ', ' B '];
Uniquearr (arr); Output:["A", "B", "C"]
Four ways to de-weigh JS arrays