JS array to heavy, Laosheng long talk, today on its summary, summed up 4 ways
Support IndexOf and foreach for the browser array object before pasting into the code Polyfill
Array.prototype.indexOf = Array.prototype.indexOf | |function(item) { for(vari = 0, j = This. length; I < J; i++) { if( This[i] = = =Item) { returni; } } return-1;} Array.prototype.forEach= Array.prototype.forEach | |function(callback, Thisarg) {if(!callback | |typeofCallback!== ' function ')return; for(vari = 0, j = This. length; I < J; i++) {Callback.call (Thisarg, This[i], I, This); }}
method One : Iterate through the array, create a new array, use IndexOf to determine if it is present in the new array, do not exist, push to the new array, and finally return the new array
1 functionRemoveduplicateditem (AR) {2 varRET = [];3 4 for(vari = 0, j = ar.length; I < J; i++) {5 if(Ret.indexof (ar[i]) = = = 1) {6 Ret.push (Ar[i]);7 }8 }9 Ten returnret; One}
method Two : Iterate through the array, save the array values with the object objects, determine if the array values have been saved in object, save the push to a new array and record the save in a object[arrayitem]=1 way
function removeDuplicatedItem2 (AR) { var tmp = {}, = []; for (var i = 0, j = ar.length; I < J; i++) { if (! Tmp[ar[i]]) { = 1; Ret.push (Ar[i]); } } return ret;}
method Three : Array subscript judgment method, iterate the array, use IndexOf to determine whether the value of the element is equal to the current index, such as equal to join
function removeDuplicatedItem3 (AR) { var ret = []; Ar.foreach (function(e, I, AR) { if (Ar.indexof (e) = = = i) { Ret.push ( e); } ); return ret;}
method Four : The array is sorted first, and then the two arrays are compared to one end to go heavy
function removeDuplicatedItem4 (AR) { var ret = [], end; Ar.sort (); = Ar[0]; Ret.push (ar[0]); for (var i = 1; i < ar.length; i++) { if (ar[i]! = end) { Ret.push (ar[i]); c19/>= ar[i]; } } return ret;}
There are other good ways to welcome the supplement.
4 ways to de-weigh JS arrays