How to realize the deduplication of javascript array
This article mainly shows you "javascript array de-duplication how to achieve", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "javascript array de-duplication how to achieve" this article.
Methods: 1, use "[... new Set (arr)]" statement; 2, use "Array.from (new Set (arr))" statement; 3, use filter and indexOf function; 4, use double for loop to check whether the value is duplicated, if there is a repetition, use push () to delete.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
Method 1: [… New Set (arr)]
Const arr = [1, 2, 3, 2, 3]; [... new Set (arr)]; / / [1,2,3]
Method 2:Array.from (new Set (arr))
Const arr = [1,2,3,2,3]; Array.from (new Set (arr)); / / [1,2,3]
Because elements in Set are unique, whether they are original values or object references, you can de-duplicate by converting an array to a Set object
The Array.from method converts a Set object into an array.
Method 3: using filter+ indexOf
Function unique (arr) {return arr.filter (function (item, index, arr) {/ / current element, first index in the original array = = current index value, otherwise return current element return arr.indexOf (item, 0) = index;}) } var arr = [1 unique (arr)) / / [1, true, true,15, false, undefined, null, NaN ", 0," a ", {… }, {... }]
Method 4: double for cycle
The easiest way to understand is to loop through elements in the outer layer and check for repetition in the inner loop.
When there are duplicate values, you can use either push () or splice ()
Function distinct (a, b) {let arr = a.concat (b); for (let item0, len=arr.length; I)