【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))
相关推荐
江城开朗的豌豆几秒前
React 跨级组件通信:避开 Context 的那些坑,我还有更好的选择!
前端·javascript·react.js
吃饺子不吃馅34 分钟前
root.render(<App />)之后 React 干了哪些事?
前端·javascript·面试
鹏多多43 分钟前
基于Vue3+TS的自定义指令开发与业务场景应用
前端·javascript·vue.js
江城开朗的豌豆1 小时前
Redux 与 MobX:我的状态管理选择心路
前端·javascript·react.js
Cosolar1 小时前
前端如何实现VAD说话检测?
前端
CodeSheep1 小时前
当了leader才发现,大厂最想裁掉的,不是上班总迟到的,也不是下班搞失联的,而是经常把这3句话挂在嘴边的
前端·后端·程序员
吃饺子不吃馅1 小时前
✨ 你知道吗?SVG 里藏了一个「任意门」——它就是 foreignObject! 🚪💫
前端·javascript·面试
IT_陈寒2 小时前
Python开发者必须掌握的12个高效数据处理技巧,用过都说香!
前端·人工智能·后端
gnip9 小时前
企业级配置式表单组件封装
前端·javascript·vue.js
一只叫煤球的猫10 小时前
写代码很6,面试秒变菜鸟?不卖课,面试官视角走心探讨
前端·后端·面试