Home >Web Front-end >Front-end Q&A >What are the 5 ways to deduplicate ES6 arrays?
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.
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);
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);
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);
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);
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);
【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!