Home > Web Front-end > JS Tutorial > Three simple solutions to deduplicate js arrays

Three simple solutions to deduplicate js arrays

angryTom
Release: 2019-12-26 17:53:31
forward
2252 people have browsed it

Three simple solutions to deduplicate js arrays

1. es6 Set to remove duplicates

function removal(arr) {
  return Array.from(new Set(arr))
}
let arr=[1,2,1,3,4,5,5]
removal(arr)//[1, 2, 3, 4]
Copy after login

2. Use filter

[Related course recommendations: JavaScript video tutorial]

function removal(arr){
  return arr.filter((item,index,arr)=>{
      return arr.indexOf(item,0) == index;
  })
}
let arr=[1,2,1,3,4,5,5]
removal(arr)//[1, 2, 3, 4]
Copy after login

3. Using reduce

let newArr = arr.reduce((prev, cur) => {
    prev.indexOf(cur) === -1 && prev.push(cur);
    return prev;
},[]);
Copy after login

This article comes from js tutorial column, welcome to learn!

The above is the detailed content of Three simple solutions to deduplicate js arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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