Home > Article > Web Front-end > Summary of JS array deduplication methods
This article mainly shares with you a summary of JS array deduplication methods. There are seven methods in total. I hope it can help everyone.
The easiest way:
1 2 3 4 ##56 7 8 9 10 11 12 13 14 15 16 17 18 |
var arr=[2,8,5,0,5,2,6,7,2]; } |
Method 1:
Double-layer loop, outer loop element, inner loop comparison value
If there is If the values are the same, they will be skipped. If they are not the same, they will be pushed into the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
##} var arra.distinct(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Advantages: simple and easy to understand
Disadvantages: high memory usage and slow speed
Method 3: Use the properties of objects that cannot be the same to deduplicate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Method 4: Recursive deduplication of arrays
Use the recursive idea
Sort first, and then compare from the end, if you encounter the same , then delete
##1 234567 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Method Five: Using indexOf and forEach
##123456789
10 11 12 13 14 15 |
|
Method 6: Use ES6's set
Set data structure, which is similar to an array, and the values of its members are all unique.
Use Array.from to convert the Set structure into an array
##1234 |
|
The expansion operator (...) uses the for...of loop internally
1 2 3 |
#let let arr = [1,2,3,3 ];
|
The following is a supplementary introduction to the method of merging arrays and removing duplicates
##1. concat() method
Idea: The concat() method combines the incoming array or non-array value with the original array to form a new array and returns it. This method will generate a new array.
2 3 4 5 |
|
2. Array.prototype.push.apply()
Idea: The advantage of this method is that it does not generate a new array.
##123456789
10 |
|
Detailed explanation of array deduplication examples in js
Six ways to deduplicate JS arrays
How to deduplicate JavaScript arrays Ways to share
The above is the detailed content of Summary of JS array deduplication methods. For more information, please follow other related articles on the PHP Chinese website!