【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))
相关推荐
房开民19 分钟前
c++总结
java·开发语言·c++
毕设源码-赖学姐33 分钟前
【开题答辩全过程】以 基于Java的医院器材管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
float_com42 分钟前
【java常用API】----- Arrays
java·开发语言
thatway198943 分钟前
闲聊-关于AI终结者的警醒
前端
努力的小郑1 小时前
突发!Claude Code 51万行源码全网裸奔:一场史诗级“开源”事故,国内大厂笑麻了
前端·后端·ai编程
七度黑光1 小时前
用 openclaw 给故障复盘打分:质量审核自动化实践
运维·服务器·前端·数据库·自动化
HashTang1 小时前
Claude Code 源码中 REPL.tsx 深度解析:一个 5005 行 React 组件的架构启示
前端·后端·ai编程
不会写DN1 小时前
PHP 中的文件读写与上传
android·开发语言·php
wendycwb2 小时前
前端城市地址根据最后一级倒推,获取各层级id的方法
前端·vue.js·typescript
LuckyTHP2 小时前
迁移shibboleth java获取shibboleth用户信息
java·开发语言