【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))
相关推荐
前端的日常10 分钟前
以下代码,那一部分运行快
前端
GeGarron11 分钟前
Drawing:专注高效画图,让每一次创作都值得被珍藏
前端
梨子同志12 分钟前
Vue v-model 指令详解
前端·vue.js
杨进军12 分钟前
简易实现 React 页面初次渲染
前端·react.js·前端框架
血舞之境14 分钟前
同名类引发问题:没见过世面导致遇见各种诡异的问题
前端
杨进军14 分钟前
实现 React 多个原生标签子节点渲染
前端·react.js·前端框架
前端的日常15 分钟前
AI 工具中,经常提到的 mcp 是什么,有哪些与前端方向结合的场景?
前端
嘉小华15 分钟前
Android 协程全景式深度解析:第四章 Flow响应式流
android·前端
Tina_晴17 分钟前
【基础篇】Promise初体验+案例分析(上)
前端·javascript·面试
7ayl18 分钟前
闭包
javascript