arr.indexOf(item)===index)" statement."/> arr.indexOf(item)===index)" statement.">
Home >Web Front-end >JS Tutorial >What are the ways to remove duplicates from javascript arrays?
Removal method: 1. Use the "Array.from(new Set(arr))" statement; 2. Use the "[...new Set(arr)]" statement; 3. Use "arr.filter( (item,index)=>arr.indexOf(item)===index)" statement.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. Array.from(new Set(arr))
const arr = [1, 2, 3, 2, 3]; Array.from(new Set(arr)); // [1, 2, 3]
Since the elements in the Set are unique, whether they are original values or object references, deduplication can be achieved by converting the array into a Set object
Array.from
Method can convert Set object into array
2, [...new Set(arr)]
const arr = [1, 2, 3, 2, 3]; [...new Set(arr)]; // [1, 2, 3]
Here is passed# The expansion syntax of ##ES6 converts the Set object into an array;
3. arr.filter((item, index) => arr.indexOf(item) == = index)
const arr = [1, 2, 3, 2, 3]; arr.filter((item, index) => arr.indexOf(item) === index); // [1, 2, 3]
indexOf method returns the first index (index) of the specified element in the array, if not, returns -1
indexOf() method are 0 1 2 1 2
arr.forEach(item => console.log(arr.indexOf(item))); // 0 1 2 1 2can be obtained through
indexOf To achieve deduplication, for example, the fourth element
2 in arr returns an index of 1 through
indexOf, but its current index subscript is 3, which is not equal, indicating that the current This
2 element has appeared before, so it should be filtered out
The above is the detailed content of What are the ways to remove duplicates from javascript arrays?. For more information, please follow other related articles on the PHP Chinese website!