数组去重,以及找出数组中重复项

// 去除数组中重复项

 let removeArr = [1,2,3,2,6,5,3,'a',3,'hello']
  //最简单的es6方法
 let x =  [...new Set(removeArr)]
 let z = Array.from(new Set(removeArr))

//原型链 indexOf方法

 let arr = [1,2,3,'hello',6,5,3,'a',3,'hello']
 let newArr = arr.filter((currentValue, index,arr)=>arr.indexOf(currentValue)===index)
 Array.prototype.extraChar = function(){
      let cacheExtraChar = []
      this.map((item)=>{
          if(cacheExtraChar.indexOf(item) === -1){
              cacheExtraChar.push(item)
          }
      })
      return cacheExtraChar
  }
  let newArrx = removeArr.extraChar()

// 获得数组中重复的项

  Array.prototype.refrain =function () {
      let repeat = [];
      [...this].sort().sort((a,b)=>{
          if(a === b && repeat.indexOf(a) === -1) repeat.push(a);
          console.log(a)
      });
      return repeat;
  }
  let newArr1 = removeArr.refrain()

// 如果数组中重复的项是对象怎么办?

 let arr = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 1, name: 'Alice'}];
 let uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
 //还有没有别的方法?
 let otherUniqueArr =arr.filter(v => !newmap.has(v.id) && newmap.set(v.id, 1))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值