JS array of methods and principles to heavy (full)

The front end of the most experienced nothing more than cycling, judgment and processing of data returned backstage, then introduce today several common methods of deduplication array.

A .ES6 grammar, new Set () method to weight

Chestnut For
the let ARR = [A, B, C, C, D];
the let new new SET = the Set (ARR);
the let newArr = Array.from (SET);
End result newArr = [a, b, c , d]
this is the easiest method to weight, but this method does not support object methods that can support some simple data format deduplication efficiency or quickly, if it is recommended to use complex data format at some methods.

II. Define a method to re-direct calls.

Create an array, the array incoming traversal, the value will not push a new array into the new array
function setarr (Array) {
var newarr = []; a new temporary array
for (var i = 0; i <array.length; ++ I) {
IF (newarr.indexOf (Array [I]) == -1) {
newarr.push (Array [I]);
}
}
return newarr;
}
var newArray = [1,2,2,3];
Console .log (setarr (newArray)); // [1, 2, 3]
this simple method of data processing can also handle complex data

III. Splice method using the Array prototype object plus a double for loop

function unique(arr) {
var i,j,len = arr.length;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
if (arr[i] == arr[j]) {
arr.splice(j, 1);
len–;
j–;
}
}
}
return arr;
}
console.log(unique([1, 1, 2, 3]))//[1,2,3]

IV. If you have more than two arrays to go heavy, then we can use concat () method or universal operator ... to merge array.

concat () method of the incoming array or array value with the original array merged to form a new array and returns. This method will produce a new array.
... method can be directly spliced two arrays.
Then call any one of the above methods to achieve deduplication array.

to sum up:

Whatever the method, we find that, in fact, the principle is similar with the cycle the judge realize, personally think it is their own method to re-package is much easy to use, can handle a variety of complex data, but the method most people package only supports some simple data de-duplication, so nothing to suggest that you can try yourself more encapsulation method, easy to use can save a file, when used directly copy a lot easier, online method too much, find it very troublesome, Well, today's share on these, and hope to give you help!

发布了4 篇原创文章 · 获赞 10 · 访问量 988

Guess you like

Origin blog.csdn.net/m0_46156566/article/details/104099335