如何在比较后的对象数组中打印额外的对象?


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"}]

Array.filter()方法回调中使用Array.some()

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);

当你比较时,实际上两个对象是不相似的。仔细看(这不是错误)

  1. id:1Q_type的值不同
  2. id为4的那个(我们都看到这个)

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"}
]
function oddIndexesOut(_arr1,_arr2){
//objects may "look" the same but if they don't point to the same thing, they're not equal.. however if i turn it into a string, things that "look" equal are equal
_arr1=_arr1.map(a=>JSON.stringify(a))
_arr2=_arr2.map(a=>JSON.stringify(a))

//comparison function(if things "look" similar)
function compare(arr1,arr2){
var x=arr1.filter(a=>!arr2.includes(a))
return x.map(a=>JSON.parse(a))
}

//the longest array is used(so that checking can be full)
if(_arr1.length>_arr2.length){
return compare(_arr1,_arr2)
}
return compare(_arr2,_arr1)
}
console.log(oddIndexesOut(array1,array2))

最新更新