Scheme one, using the IndexOf method of the array (i.)
Principle
Declare an empty array first, then loop the array members, use the array's IndexOf method to determine whether the current member exists in the new array, if not exist then push in, and finally return the new array to get a de-heavy array!
The code is as follows
function () { var newArr = [], = 0, this. length; for (; i < Len; i++) { varThis[i]; if (Newarr.indexof (temparr) = = =-1) { newarr.push (Temparr); } } return newArr;};
Scenario two, using the IndexOf method of the array (ii)
Principle
Creates a new array and inserts the first element, polls the array, determines the position of the current element in the arrays, and does not add if no I is present in the array!
The code is as follows:
function () { var newArr = [this [0]], = 1, this. length; for (; i < Len; i++) { varThis[i]; if (this. IndexOf (temparr) = = = i) { newarr.push (Temparr); } } return newArr;};
Scenario three, the use of the object's hash value
Principle:
Create an Obj object to hold the current value, poll the array, judge the value in the Obj object, and add it if it does not exist! This method uses the object's hash to carry on the performance enhancement! Compared to the previous two methods, the performance of the method is a bit higher!
The code is as follows:
Array.prototype.unique =function() { varobj ={}, NEWARR=[], I= 0, Len= This. Length; for(; i < Len; i++) { varTemparr = This[i]; if(!Obj[temparr]) {Obj[temparr]=true; Newarr.push (Temparr); } } returnnewArr;};
Method four, using the array to sort out the weight
Principle
Sorts the array first, calling the sort method inside the arrays. The array is then polled to determine if the current element is the last item of the new one, or if it is not the first time it is added, push it directly in, or skip it.
The code is as follows:
Array.prototype.unique =function() { This. sort (); varNEWARR = [ This[0]], I= 0, Len= This. Length; for(; i < Len; i++) { varTemparr = This[i]; if(Temparr!== newarr[newarr.length-1]) {Newarr.push (Temparr); } } returnnewArr;};
Method Five, using regular matching to carry out the weight
Principle
The array is converted into a string of the specified symbol segmentation, followed by a series of substitution operations, and then split into a new array. (Note: The original array member type int is a string type after the operation, use CAUTION!!!!) )
The code is as follows:
function () { returnthis. Sort (). Join (",,"). Replace (/(, |^) ([^,]+) (,, \2) + (, |$)/g, "$1$2$4"). Replace (/,,+/g, ","). Replace (/,$/, ""). Split (",");
JavaScript Array de-weight