【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))
相关推荐
csbysj20202 小时前
jQuery 删除元素
开发语言
xxy-mm2 小时前
Javascript 中的继承
开发语言·javascript·ecmascript
锋行天下4 小时前
公司内网部署大模型的探索之路
前端·人工智能·后端
quikai19814 小时前
python练习第二组
开发语言·python
1024肥宅5 小时前
手写 EventEmitter:深入理解发布订阅模式
前端·javascript·eventbus
AI视觉网奇5 小时前
Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr
开发语言·c++·算法
wjs20245 小时前
并查集快速合并
开发语言
free-elcmacom5 小时前
MATLAB与高等数学<1>一道曲面积分题的几何直观
开发语言·数学建模·matlab·高等数学
LaoZhangGong1235 小时前
深度学习uip中的“psock.c和psock.h”
c语言·开发语言
Tony Bai5 小时前
Go 安全新提案:runtime/secret 能否终结密钥残留的噩梦?
java·开发语言·jvm·安全·golang