前端数组去重的几种方式



一、两层for循环

代码如下(示例):

let arr = [1, 2, 2, 'a', 'b', 'a', 'c', false, true, undefined, undefined, false, NaN]
for (let i = 0;i < arr.length; i++) {
  for (let j = i+1; j < arr.length; j++) {
    if (arr[i] === arr[j]) {
      arr.splice(i, 1)
    }
  }
}
console.log(arr) // [ 1, 2, 'a', 'b', 'c', false, true, undefined, NaN ]

二、使用new Set

最简单的,一行代码搞定,代码如下(示例):

let arr = [1, 2, 2, 'a', 'b', 'a', 'c', false, true, undefined, undefined, false, NaN]
console.log([...new Set(arr)]) // [ 1, 2, 'a', 'b', 'c', false, true, undefined, NaN ]

三、使用数组的indexOf方法

创建一个新的数组,将原来的数组中的数据加到新的数组中,通过indexof来判断新数组是否有这个数据,如果有就不添加,没有就添加

let arr = [1, 2, 2, 'a', 'b', 'a', 'c', false, true, undefined, undefined, false, NaN]
let newArr = []

for (let i = 0; i < arr.length; i++) {
  if (newArr.indexOf(arr[i]) == -1){
    newArr.push(arr[i])
  }
}

console.log(newArr)  // [ 1, 2, 'a', 'b', 'c', false, true, undefined, NaN ]

四、使用数组的filter方法

使用filter结合indexof,如果当前索引等于indexof返回的索引,就代表没有重复项,如果不等于说明后面有重复

let arr = [1, 2, 2, 'a', 'b', 'a', 'c', false, true, undefined, undefined, false ]

const newArr = arr.filter((item, index) => {
  return arr.indexOf(item) === index
})

console.log(newArr) // [ 1, 2, 'a', 'b', 'c', false, true, undefined ]

五、使用对象的方式

用数组的值作为对象的key,因为对象的key值不能重复,创建完对象后,直接取key就是去重后的数组

let arr = [1, 2, 2, 'a', 'b', 'a', 'c', false, true, undefined, undefined, false ]
let obj = {}

for (let i = 0; i < arr.length; i++){
  if (!obj[arr[i]]) {
    obj[arr[i]] = 1
  } else {
    obj[arr[i]]++
  }
}
console.log(Object.keys(obj)) // [ '1', '2', 'a', 'b', 'c', 'false', 'true', 'undefined' ]

欢迎批评指正

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值