In the array operation will often encounter the problem of removing duplicates, the following is a brief introduction to the method of array, and its execution efficiency
Method One
Using two loops
Principle: Take the current and the back of the ratio, if the back of a repeat of the kill
But we found the last item in the array, and there was nothing behind it, so he didn't have to compare it to the back, so we just need to loop arr.length-1 time.
var arr=[1,3,5,3,5,3,4,1,3,5,3,5,3,41,3,5,3,5,3,4,1,3,5,3,5,3,4];
for (Var i=0;i<arr.length-1;i++) {
var curitem=arr[i];//current Item
for (Var j=i+1;j<arr.length;j++) {
if (Curitem==arr[j]) {
Arr.splice (j,1);
j--;
}
}
}
Console.log (arr);
This method uses two cycles, which brings a lot of pressure to the browser, and the number of times the factorial of the length of the array.
So consider substituting objects (the object's property name does not repeat) method two
var arr=[1,3,5,3,5,3,4,6,2,2,2,1];
var len=arr.length;
var obj={};
for (Var i=0;i<len;i++) {
var cur=arr[i];//current Item
Obj[cur]=cur;
}
var list=[];
for (key in obj) {
List.push (Obj[key])
}
Console.log (list);
This method performs more efficiently, but is recycled two times
Another approach: Method three
Principle: loop array, which saves each item in the array as the attribute name and attribute value of the Obj object,
But we found that if the attribute name already exists in the Obj object, then the array repeats, so we delete the duplicate items
var arr=[1,3,5,3,5,3,4,1,3,5,3,5,3,41,3,5,3,5,3,4,1,3,5,3,5,3,4];
var obj={};
for (Var i=0;i<arr.length;i++) {
var cur=arr[i];//current Item
if (obj[cur]==cur) {
Arr.splice (i,1);
i--
}else{
Obj[cur]=cur;
}
}
Obj=null;
Console.log (arr);
This method also uses two cycles, think about it and use a method to achieve the weight.
Package method two to method
var arr=[1,3,5,3,5,3,4,6,2,2,2,1,7,84,34,634];
Array.prototype.arr_unique=function () {
var len=this.length;
var obj={};
for (Var i=0;i<len;i++) {
var cur=this[i];//current Item
Obj[cur]=cur;
}
var list=[];
for (key in obj) {
List.push (Obj[key])
}
return list;
};
Console.log (Arr.arr_unique ());
The method of three packages of methods
var arr=[1,3,5,3,5,3,4,6,2,2,2,1,7,84,34,634];
Array.prototype.arr_unique=function () {
var obj={};
for (Var i=0;i<this.length;i++) {
var cur=arr[i];//current Item
if (obj[cur]==cur) {
alert (1111);
Arr.splice (i,1);
i--
}else{
Obj[cur]=cur;
}
}
Obj=null;
return this;
};
Console.log (Arr.arr_unique ());