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)

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值