js遍历两个数组找出不同的元素

前提:有两个数组,数组A和数组B,假设数组B是数组A的子集,遍历这两个数组,然后把数组B中缺少的数组A的元素添加到数组B中
如:
数组A:

let arrA = [
	{ 
		id: 1, 
		data: [
			{times: 6, type: 1},
			{times: 23, type: 2},
			{times: 6, type: 3}
		]
	},
	{ 
		id: 2, 
		data: [
			{times: 3, type: 1},
			{times: 8, type: 3}
		]
	},
	{ 
		id: 3, 
		data: [
			{times: 6, type: 1},
			{times: 2, type: 3}
		]
	},
	{ 
		id: 4, 
		data: [
			{times: 5, type: 2},
			{times: 1, type: 3}
		]
	},
	{ 
		id: 5, 
		data: [
			{times: 3, type: 2}
		]
	}
]

数组B:数组B的由来是遍历数组A,再遍历data,找到 type: 1 的元素取出来

let arrB = [
	{ 
		id: 1, 
		times: 6
	},
	{ 
		id: 2, 
		times: 3
	},
	{ 
		id: 3, 
		times: 6
	},
]

接下来就是补全 数组B:arrB,如果不存在id,则 times: 0

遍历两个数组找出不同的元素

getFor(allArr, lessArr) {
  let arr = []
  if (lessArr.length !== allArr.length) {
    for (let i = 0; i < allArr.length; i++) {
      let isExist = false // 声明一个boolean值,不然循环不对
      for (let j = 0; j < lessArr.length; j++) {
        if (lessArr[j].id=== allArr[i].id) {
          isExist = true
          break
        }
      }
      if (!isExist) {
        arr.push({
          id: allArr[i].id,
          times: 0
        })
      }
    }
    return arr
  } else {
    return []
  }
}
...
arrB= [...arrB, ...this.getFor(arrA, arrB)]
...

最终 arrB :

arrB = [
	{ 
		id: 1, 
		times: 6
	},
	{ 
		id: 2, 
		times: 3
	},
	{ 
		id: 3, 
		times: 6
	},
	{ 
		id: 4, 
		times: 0
	},
	{ 
		id: 5, 
		times: 0
	},
]

找出2个数组不同的元素

数组对象也是一样

const oldVal = ['4620214765279510529', '4626834100420870145']
const newVal = ['4620214765279510529']
const res = oldVal.filter((e) => !newVal.some((e2) => e2 === e));
console.log(res)  // ['4626834100420870145']
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值