js数组去重

1. includes

新建一新空数组,遍历传入数组,值不在新数组就push进该新数组中,includesindexOf 原理相同。

let reg = [1, 1, 2, 2, 22, 4, 4, 6, 6, 8] 
let arr=[]
    reg.forEach(item => {
      if (!arr.includes(item)) {
         arr.push(item)
       }
    })

2. indexOf

let arr=[]
    reg.forEach(item => {
      if (arr.indexOf(item)==-1) {
        arr.push(item)
      }
    })

3. reduce

语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • total:初始值,或者计算之后的返回值
  • currentValue:当前元素
  • currentIndex:当前元素的索引
  • arr:当前元素所属的数组对象
  • initialValue:传递给函数的初始值
reg.reduce((total, value) => {
       return total.includes(value)?total:total.concat(value)
    }, [])

Set

ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构。我们发现得到的结果,是一个对象,并不是数组,可以使用Array.from(),它可以把类数组对象、可迭代对象转化为数组。

  • 展开运算符和set结构
let cie=[...new Set(reg)]
  • Array.from()来实现方法扩展运算符的功能
let cie=Array.from(new Set(reg))
  • Set 可以很容易地实现并集(Union)、交集(Intersect)和差集(Difference)
let a=new Set([1,2,3])
let b=new Set([2,4,5])

//并集
let union = new Set([...a,...b])
//Set(5) {1, 2, 3, 4, 5}

// 交集 
let intersection = new Set([...a].filter(x => b.has(x)));
//Set(1) {2}

// 差集
let difference = new Set([...a].filter(x => !a.has(x)));
//Set(2) {1, 3}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值