【JS】数组去重

方式一:使用 Set

typescript 复制代码
const handler = (array) => {
  return [...new Set(array)];
}
const array = [1, 2, 2, 3, 3, 4, 5, 5];
console.log(handler(array)); // [1, 2, 3, 4, 5]

方式二:使用filter

typescript 复制代码
const handler = (array) => {
  return array.filter((item, index) => array.indexOf(item) === index);
}
const array = [1, 2, 2, 3, 3, 4, 5, 5];
console.log(handler(array)); // [1, 2, 3, 4, 5]

方式三:使用reduce

typescript 复制代码
const handler = (array) => {
  return array.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
}
const array = [1, 2, 2, 3, 3, 4, 5, 5];
console.log(handler(array)); // [1, 2, 3, 4, 5]

方式四:复杂类型也需要去重

由于严格相等对于复杂类型是判断,所以多个复杂类型的内容相同时,也需要去重。

声明判断两个值是否相等的方法

typescript 复制代码
function isEqual(a, b) {
  // 如果 a 和 b 是基本类型或者相等,则直接返回 true
  if (a === b) {
    return true;
  }

  // 如果 a 和 b 是对象
  if (typeof a === 'object' && typeof b === 'object') {
    // 如果 a 和 b 的键数量不相等,则直接返回 false
    if (Object.keys(a).length !== Object.keys(b).length) {
      return false;
    }

    // 递归比较对象的每个键值对
    for (let key in a) {
      if (!isEqual(a[key], b[key])) {
        return false;
      }
    }
    return true;
  }

  // 如果 a 和 b 是数组
  if (Array.isArray(a) && Array.isArray(b)) {
    // 如果数组长度不相等,则直接返回 false
    if (a.length !== b.length) {
      return false;
    }

    // 递归比较数组的每个元素
    for (let i = 0; i < a.length; i++) {
      if (!isEqual(a[i], b[i])) {
        return false;
      }
    }
    return true;
  }

  // 其他情况返回 false
  return false;
}

根据上面的函数返回值作为判断条件

typescript 复制代码
function handler(arr) {
  let result = []
  for (let i = 0; i < arr.length; i++) {
    let isFind = false
    for (let j = 0; j < result.length; j++) {
      if (isEqual(result[j], arr[i])) {
        isFind = true
        break
      }
    }
    if (!isFind) {
      result.push(arr[i])
    }
  }
  return result
}
let a = [[1, 2], [1, 2], ["1", "2"], [1, "2"], [1, 2, 3]]
console.log(handler(a))
相关推荐
金木讲编程4 分钟前
Claude、Agent与Copilot协作生成Angular应用
前端·ai编程
怪兽201431 分钟前
fastjson在kotlin不使用kotlin-reflect库怎么使用?
android·开发语言·kotlin
ClearLiang31 分钟前
Kotlin-协程的挂起与恢复
开发语言·kotlin
彭同学学习日志36 分钟前
Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘
android·开发语言·kotlin
振华OPPO40 分钟前
Vue:“onMounted“ is defined but never used no-unused-vars
前端·javascript·css·vue.js·前端框架
海域云赵从友41 分钟前
破解跨境数据传输瓶颈:中国德国高速跨境组网专线与本地化 IP 的协同策略
开发语言·php
咚咚王者1 小时前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
欧雷殿1 小时前
在富阳银湖成立地域化的软件研发团队
前端·程序员·创业
深蓝海拓1 小时前
使matplot显示支持中文和负号
开发语言·python
狂炫冰美式2 小时前
前端实时推送 & WebSocket 面试题(2026版)
前端·http·面试