首页 > 解决方案 > 比较后如何在对象数组中打印额外的对象?

问题描述

const array1 = [
  {id: 1, Q_type: "AL"},
  {id: 2, Q_type: "BL"},
  {id: 3, Q_type: "CL"},
  {id: 4, Q_type: "DL"}
]
const array2 = [
  {id: 2, Q_type: "BL"},
  {id: 3, Q_type: "CL"},
  {id: 4, Q_type: "DL"}
]

const arrAfterComparison = array1.filter(val => !array2.includes(val))

我正在尝试比较array1array2获取这两个数组中都不存在的对象

预期产出

arrAfterComparison = [{id:1,Q_type:"AL"}]

标签: javascriptarrays

解决方案


使用Array.some()内部Array.filter()方法回调。

const array1 = [
  {id: 1, Q_type: "AL"},
  {id: 2, Q_type: "BL"},
  {id: 3, Q_type: "CL"},
  {id: 4, Q_type: "DL"}
]
const array2 = [
  {id: 2, Q_type: "BL"},
  {id: 3, Q_type: "CL"},
  {id: 1, Q_type: "DL"}
]

const output = array1.filter(item => !array2.some(a => a.Q_type === item.Q_type))
console.log(output);


推荐阅读