I believe that we all know the online about the array of JavaScript in a lot of ways, this article summarizes the JavaScript array of various ways to weight, I believe this article on everyone to learn and use JavaScript has a certain reference value, there is a need for the following to see together.
Objective
When it comes to JavaScript development, there are often problems with the duplication of array elements, and the JavaScript array does not directly provide a way to solve this problem, but it also needs to be implemented by itself. This article summarizes the various ways to de-weight arrays in JavaScript, and let's look at them together.
Method one takes advantage of attributes that are not duplicated by object properties
Array.prototype.distinct = function () { var arr = This, i, obj = {}, result = [], len = Arr.length;
for (i = 0; i< arr.length; i++) { if (!obj[arr[i]]) { //If it can be found, proving that the array element repeats obj[arr[i]] = 1; Result.push (Arr[i]); } } return result;};
Method two two-layer loop, outer loop element, inner loop time comparison value
Array.prototype.distinct = function () { var arr = this, result = [], I, j, len = arr.length; for (i = 0; l < len; i++) {for (j = i + 1; j < Len; J + +) { if (arr[i] = = = Arr[j]) { j = ++i; } } Result.push (Arr[i]); } return result;}
Method three recursive return of the array
Array.prototype.distinct = function () { var arr = this, len = arr.length; Arr.sort (A, b) { ///array for easy comparison of return-A- B; }) function Loop (index) { if (index >= 1) { if (arr[index] = = = Arr[index-1]) { arr.splice (index,1); } Loop (index-1); Recursive loop function for de-weight } } loop (len-1); return arr;};
Method four uses indexof and foreach
Array.prototype.distinct = function () { var arr = this, result = [], len = arr.length; Arr.foreach (function (v, I, arr) { ///here using the Map,filter method can also implement var bool = arr.indexof (v,i+1); Search for duplicate if (bool = =-1) { Result.push (v)} ) from the next index value passed in the parameter return result;};
Method five using the set of ES6
function Dedupe (array) { return Array.from (new Set (array));} Dedupe ([1,1,2,3])//[1,2,3]
Method six expansion operators (...) Internal use of For...of loops
Let arr = [3,5,2,2,5,5];let unique = [... new Set (arr)]; [3,5,2]
Http://www.jb51.net/article/94046.htm
Summarize the various methods of de-weight for arrays in JavaScript