JS数组对象去重同时判断两个属性是否相同

arr=[
 {
    maxDeptCode: "md3"
    maxDeptName: "泡泡"
    minDeptCode: "md301"
    minDeptName: "泡泡少儿"
    schoolId: 1
    schoolName: "北京"
 },
 {
    maxDeptCode: "md2"
    maxDeptName: "中学"
    minDeptCode: "md201"
    minDeptName: "中学一对一"
    schoolId: 1
    schoolName: "北京"
 },{
    maxDeptCode: "md3"
    maxDeptName: "泡泡"
    minDeptCode: "md301"
    minDeptName: "泡泡少儿"
    schoolId: 1
    schoolName: "北京"
 },
]

1.方法一

function process(arr) {
    // 缓存用于记录
    const cache = [];
    for (const t of arr) {
        // 检查缓存中是否已经存在
        if (cache.find(c => c.maxDeptCode === t.maxDeptCode && c.minDeptCode === t.minDeptCode)) {
            // 已经存在说明以前记录过,现在这个就是多余的,直接忽略
            continue;
        }
        // 不存在就说明以前没遇到过,把它记录下来
        cache.push(t);
    }

    // 记录结果就是过滤后的结果
    return cache;
}

2.方法二

function process2(arr) {
    // 需要一个字典,可以用 Set/WeakSet 或者就简单的 JS 对象
    const dict = {};

    // 过滤的过程中完善 dict
    return arr.filter(t => {
        // 根据 max 和 min 来生成唯一识别的关键字
        // 这里采用的办法是使用一个不会出现在两个数据中的字符 `|` 来连接
        const key = [t.maxDeptCode, t.minDeptCode].join("|");

        // 检查如果字典中已经存在,那这个数据就过滤掉,不需要了
        if (dict[key]) {
            return false;
        }

        // 如果字典不不存在,加入字典,同时把数据保留下来(返回 true)
        dict[key] = true;
        return true;
    });
}

3.方法三

let result = arr.reduce((init, current) => {
      const maxCode = current.maxDeptCode
      const minCode = current.minDeptCode
      const index = `${maxCode}${minCode}`

      if (init.length === 0 || !init[index]) {
        init[index] = current
      }
      return init
    }, [])
    console.log(result)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值