In the array operation often encounter the problem of removing duplicates, the following is a brief introduction to the method of array deduplication, and its implementation efficiency
Method One
Use two loops
Principle: Take the current and the ratio behind him, if there are duplicates on the back to kill
But we found the last item in the array, and there was nothing behind it, so he didn't have to compare it with the back, so we just had to loop arr.length-1 times.
vararr=[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(vari=0;i<arr.length-1;i++){ varCuritem=arr[i];//Current Item for(varj=i+1;j<arr.length;j++){ if(curitem==Arr[j]) {Arr.splice (J,1); J--; }}} console.log (arr);
This method uses two cycles, which put a lot of pressure on the browser, the number of times the factorial of the length of the array.
So consider an object substitution (the object's property name is not duplicated) 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 loops two times
Take another approach: Method three
Principle: The loop array, which saves each item in the array as the property name and attribute value of the Obj object,
But we found that if the property name already exists in the Obj object, it means that the array is duplicated, so we delete the duplicates.
vararr=[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]; varobj={}; for(vari=0;i<arr.length;i++){ varCur=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, thinking carefully about how to use a single implementation of the method of de-weight.
Method Two Encapsulation method
vararr=[1,3,5,3,5,3,4,6,2,2,2,1,7,84,34,634]; Array.prototype.arr_unique=function (){ varlen= This. Length; varobj={}; for(vari=0;i<len;i++){ varCur= This[i];//Current Itemobj[cur]=cur; } varlist=[]; for(Keyinchobj) {List.push (Obj[key])}returnlist;}; Console.log (Arr.arr_unique ());
Method Three Encapsulation method
vararr=[1,3,5,3,5,3,4,6,2,2,2,1,7,84,34,634]; Array.prototype.arr_unique=function (){ varobj={}; for(vari=0;i< This. length;i++){ varCur=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 ());
Three common methods for JavaScript array de-weight and their performance comparison