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?

What are the ways to remove duplicates from javascript arrays?

青灯夜游
青灯夜游Original
2021-06-22 16:42:301776browse

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.

What are the ways to remove duplicates from javascript arrays?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Several ways to remove duplicates from JavaScript arrays

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

So the index values ​​returned by each element in the arr array here through the

indexOf() method are 0 1 2 1 2

arr.forEach(item => console.log(arr.indexOf(item))); // 0 1 2 1 2

can 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

[Related recommendations:

javascript learning tutorial]

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn