0
点赞
收藏
分享

微信扫一扫

JS 数组去重的多种方法


JS 数组去重的多种方法_数组

  • 1. 前言
  • 2. 普通方法数组去重
  • 3. filter + indexOf
  • 4. ES6 的 new Set()
  • 5. 需要注意的问题

1. 前言

本文提供两个数组变量供测试使用

const array = ['html', 'css', 'js', 'css']const resArr = ['html', 'css', 'css', [1], [1]]


2. 普通方法数组去重

下面列举几种数组去重的方法思路都一样:

遍历数组,将数组元素添加到新数组中,新数据中已有该元素,则不添加到新数组

// for + indexOfconst res = [];for (let index = 0; index < array.length; index++) {    res.indexOf(array[index]) === -1 && res.push(array[index])}// forEach + indexOfconst res = [];array.forEach(item => {    res.indexOf(item) === -1 && res.push(item)})// reduce + includesconst res = array.reduce((total, item) => {    !total.includes(item) && total.push(item)    return total;}, [])

3. filter + indexOf

使用 filter + indexOf 的方式可以使代码变为更简洁

filter() 方法过滤数组,只保留满足条件的元素。indexOf() 方法判断元素首次出现的下标是否为当前遍历的下标


// ['html', 'css', 'js']const res = array.filter((item, index) => array.indexOf(item) === index)


4. ES6 的 new Set()

利用 Set 结构不能接收重复数据的特点


const res = [...new Set(array)]


5. 需要注意的问题

当数组中存在引用类型的元素时,引用类型元素无法保持唯一性


const resArr = ['html', 'css', 'css', [1], [1]]// ['html', 'css', 'css', [1], [1]]const res = resArr.filter((item, index) => resArr.indexOf(item) === index)


 

举报

相关推荐

0 条评论