Original: Three common methods for JavaScript array de-weight and its performance comparison
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.
1 vararr=[1,3,5,3,5];2 3 varlen=arr.length;4 for(varI=0; i<len-1; i++){5 varCuritem=arr[i];//Current Item6 for(varj=i+1; j<len;j++){7 if(curitem==Arr[j]) {8Arr.splice (J,1);9j--;Ten } One } A } -Console.log (arr);
Execution efficiency is not flattering, my computer is more than this can not be carried out
So consider an object substitution (the object's property name is not duplicated) method two
1 vararr=[1,3,5,3,5,3,4,6,2,2,2,1];2 varlen=arr.length;3 varobj={};4 5 for(varI=0; i<len;i++){6 varCur=arr[i];//Current Item7obj[cur]=cur;8 }9 varlist=[];Ten for(Keyinchobj) { One List.push (Obj[key]) A } -Console.log (list);
This method performs more efficiently, and many of the contents of the array do not crash in the browser, but the loop uses 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.
1 vararr=[1,3,5,3,5,3,4];2 varlen=arr.length;3 varobj={};4 for(varI=0; i<len;i++){5 varCur=arr[i];//Current Item6 if(obj[cur]==cur) {7Arr.splice (I,1);8i--9}Else{Tenobj[cur]=cur; One } A - } -obj=NULL; theConsole.log (arr);
But after testing this method and method of efficiency is similar, do not believe can try, it is recommended method two
Encapsulation of this into a method
1 vararr=[1,3,5,3,5,3,4,6,2,2,2,1,7, -, the,634];2Array.prototype.arr_unique=function () {3 varlen= This. Length;4 varobj={};5 6 for(varI=0; i<len;i++){7 varCur= This[i];//Current Item8obj[cur]=cur;9 }Ten varlist=[]; One for(Keyinchobj) { A List.push (Obj[key]) - } - the returnlist; - - }; - +Console.log (Arr.arr_unique ());
Limited ability, hope to bring you help
Three common methods for JavaScript array de-weight and their performance comparison