Array.prototype.unique1 =function(){ varn = []; for(vari = 0; I < This. length; i++) { if(N.indexof ( This[i]) = =-1) n.push ( This[i]); } returnN;} Array.prototype.unique2=function(){ varn = {},r=[]; for(vari = 0; I < This. length; i++) { if(!n[ This[i]]) {n[ This[i]] =true; R.push ( This[i]); } } returnR;} Array.prototype.unique3=function(){ varn = [ This[0]]; for(vari = 1; I < This. length; i++) { if( This. IndexOf ( This[i]) = = i) N.push ( This[i]); } returnN;} Array.prototype.unique4=function(){ This. sort (); varre=[ This[0]]; for(vari = 1; I < This. length; i++) { if( This[i]!== re[re.length-1]) {Re.push ( This[i]); } } returnre;} Array.prototype.unique5=function(){ varSelf = This; var_a = This. Concat (). sort (); _a.sort (function(A, b) {if(A = =b) { varn =Self.indexof (a); Self.splice (N,1); } }); returnSelf ;}; Array.prototype.unique6=function(){ return This. Reduce (function(P, c) {if(P.indexof (c) < 0) P.push (c); returnp; }, []); };
Performance test: (Running with an array of 10000 random numbers)
Method 1 Used 349ms
Method 2 Used 5ms
Method 3 Used 442ms
Method 4 Used 15ms
Method 5 Used 13MS
Method 6 Used 424ms
So, the best idea to the unique an array is to use a "hash map" to check if an item is repeated.
There is a demo page:http://php.js.cn/down/sample/array.html
Original address: 6 ways to get unique values of a Array in Javascript
Go 6 ways to weigh JavaScript