Home > Web Front-end > Front-end Q&A > What are the 5 ways to deduplicate ES6 arrays?

What are the 5 ways to deduplicate ES6 arrays?

青灯夜游
Release: 2022-08-30 17:35:30
Original
11848 people have browsed it

5 methods: 1. Use Set structure and Array.from(), syntax "Array.from(new Set(arr))"; 2. Use Set structure and expansion operator, syntax "[. ..new Set(arr)]"; 3. Traverse the array and use indexOf() to remove duplicates in the loop body.

What are the 5 ways to deduplicate ES6 arrays?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

5 ES6 array deduplication methods

1. Set data structure and Array.from() deduplication

let arr=[1,2,3,3,2,"1",0,undefined,undefined];
let newArr=Array.from(new Set(arr));
console.log(newArr);
Copy after login

What are the 5 ways to deduplicate ES6 arrays?

2. Set data structure and spread operator "..." to remove duplicates

let arr=[1,2,3,3,2,"1",0,1,2];
let newArr=[...new Set(arr)];
console.log(newArr);
Copy after login

What are the 5 ways to deduplicate ES6 arrays?

3. Use the single-layer loop indexOf to remove duplicates

var arr=[1,2,3,3,2,"1",0,1,2,undefined,undefined];
var newArr = [];
for(let i = 0;i <arr.length;i++){
    if(newArr.indexOf(arr[i]) ===-1) {
      newArr.push(arr[i]);
    }
}
console.log(newArr);
Copy after login

What are the 5 ways to deduplicate ES6 arrays?

4. Use the includes method of the array to remove duplicates

var arr=[1,2,3,3,2,"1",0,1,2,undefined,undefined];
var newArr = [];
for(let i = 0;i <arr.length;i++){
  if(!newArr.includes(arr[i])){
    newArr.push(arr[i]);
  }
}
console.log(newArr);
Copy after login

What are the 5 ways to deduplicate ES6 arrays?

5. Use the filter method of the array to remove duplicates

var arr=[1,2,3,3,2,"1",0,1,2,undefined,undefined];
var newArr = arr.filter((item,index)=> {
  return arr.indexOf(item,0) === index;
});
console.log(newArr);
Copy after login

What are the 5 ways to deduplicate ES6 arrays?

【Related Recommended: javascript video tutorial, web front-end

The above is the detailed content of What are the 5 ways to deduplicate ES6 arrays?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template