Objective
When you do JavaScript development, you often encounter the problem of duplication of array elements, and JavaScript array does not provide a way to solve the problem directly, it needs to be implemented on its own. This article summarizes the various ways to weight the array in JavaScript, so let's look at it together.
Method A feature that is not duplicated by object attributes
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 able to find it, prove that the array element repeats the
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;< C27/>for (i = 0; i < len; i++) {for
(j = i + 1; j < Len; J +) {
if (arr[i] = = Arr[j]) {
j = ++i;
}
}
Result.push (Arr[i]);
return result;
}
Method three array recursion weight
Array.prototype.distinct = function () {
var arr = this,
len = arr.length;
Arr.sort (function (a,b) { //array is sorted to facilitate 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 to go heavy
}
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 Map,filter method can also implement
var bool = arr.indexof (v,i+1); Start looking for duplicate if
(bool = = 1) {
Result.push (v);
}
)
from the next index value of the incoming parameter return result;
};
Method Five utilizes the ES6 set
function Dedupe (array) {return
array.from (new Set (array));
}
Dedupe ([1,1,2,3])//[1,2,3]
Method six extensions operator (...) Internal use of For...of loops
Let arr = [3,5,2,2,5,5];
Let unique = [... new Set (arr)]; [3,5,2]
Summarize
Well, the above is the entire content of this article, the individual prefers to use a method, will not modify the original array, I hope this article for everyone can help, if there is doubt you can message exchange.