js数组去重常用的方法

目录

一、Set

二、for循环+数组的indexOf方法

三、sort默认排序,当前元素与前一个元素对比

四、两个for循环(会改变原数组)

五、使用数组reduce方法


一、Set

  const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
  function uni(source) {
    return [...new Set(source)]
  }
  console.log(uni(target))

二、for循环+数组的indexOf方法

  const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
  function uni2(source) {
    const newArray = []
    for (let i = 0; i < source.length; i++) {
      // 如果newArray中没有该元素,则添加;
      if (newArray.indexOf(source[i]) === -1) {
        newArray.push(source[i])
      }
    }
    return newArray
  }
  let res = uni2(target)
  conosole.log(res)

三、sort默认排序,当前元素与前一个元素对比

const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']  
function uni(source) {
   const res = []
   // 默认排序
   const arr1 = source.sort()
   for (let i = 0; i < arr1.length; i++) {
     if (arr1[i] !== arr1[i - 1]) {
       res.push(arr1[i])
     }
   }
   return res
 }
 let res = uni(target)
 console.log(res)

四、两个for循环

注:此方法会改变原数组

 const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
  for (let i = 0; i < target.length; i++) {
    for (let j = i + 1; j < target.length; j++) {
      if (target[i] === target[j]) {
        target.splice(j, 1)
        // 删掉后,后面所有的元素的索引会减一,所以需要j--
        j--
      }
    }
  }
  console.log(target)

五、使用数组reduce方法

  const target = [1, 2, 34, 5, 6, 3, 23, 3, 23, 23, 23, 23, 2, 34, 6, 's', 'a', 's', 'b', 'o', 'p', 'o']
//默认值为[]空数组,Array.reduce返回的是一个新数组,直接将这个新数组返回
  function unique(array) {
    return array.reduce((arr, current) => {
      if (arr.indexOf(current) === -1) {
        arr.push(current)
      }
      return arr
    }, [])
  }
  let res = unique(target)
  console.log(res)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值