如何比较两个不同长度的对象数组?

时间:2019-03-12 10:03:39

标签: javascript

我在角度应用程序上工作,我必须比较2个对象数组:

ar1 = [{id: 2, itemId: 1},
    {id: 5, itemId: 3},
    {id: 18,itemId: 13},
    {id: 16,itemId: 14}]

ar2 = [{id: 13, itemId: 1},
    {id: 12, itemId: 14}]

我尝试做这样的事情:

for(let i = 0 ; i < this.ar1.length ; i++){
    if(this.ar2[i] != undefined){
        if(this.ar1[i].itemId == this.ar2[i].itemId){
            console.log("in and ==itemId",this.ar2[i])
        }
        else{
            console.log("in and !=itemId",this.ar1[i])
        }
    }
    else{
        console.log("undefined",this.ar1[i])
    }
}

这是给我的回报:

in and ==itemId {id: 13, itemId: 1}
in and !=itemId {id: 5, itemId: 3}
undefined {id: 18, itemId: 13}
undefined {id: 16, itemId: 14}

我想要一个函数,它可以告诉我哪个对象在2个数组中,哪个对象不在2个数组中。

这不是重复的原因,我不想看到2个对象数组之间的差异,但要查看itemId是否相同并获取具有相同itemId的对象。

3 个答案:

答案 0 :(得分:2)

您遍历了两个数组,发现它的arr1的id是否存在于arr2中

ar1 = [{
    id: 2,
    itemId: 1
  },
  {
    id: 5,
    itemId: 3
  },
  {
    id: 18,
    itemId: 13
  },
  {
    id: 16,
    itemId: 14
  }
]

ar2 = [{
    id: 13,
    itemId: 1
  },
  {
    id: 12,
    itemId: 14
  }
]

for (let i = 0; i < this.ar1.length; i++) {
  id = false;
  for (let j = 0; j < this.ar2.length; j++) {
    if (this.ar1[i].itemId == this.ar2[j].itemId) {
      id = true
      data = this.ar2[j];
    }

  }
  if (id) {
    console.log("in and ==itemId", data)
  } else {
    console.log("in and !=itemId", this.ar1[i])
  }
}

答案 1 :(得分:0)

就是这样:

const ar1 = [
  { id: 2, itemId: 1 },
  { id: 5, itemId: 3 },
  { id: 18, itemId: 13 },
  { id: 16, itemId: 14 },
]

const ar2 = [{ id: 13, itemId: 1 }, { id: 12, itemId: 14 }]
const inTwoArray = []
const notInTwoArray = []
ar1.forEach(el => {
  if (ar2.find(el1 => el1.itemId === el.itemId)) {
    inTwoArray.push(el)
  } else {
    notInTwoArray.push(el)
  }
})

console.log(inTwoArray)
console.log(notInTwoArray)

答案 2 :(得分:0)

以下代码段将帮助您找到itemId常见的位置-

let ar1 = [{ id: 2, itemId: 1 },
    { id: 5, itemId: 3 },
    { id: 18, itemId: 13 },
    { id: 16, itemId: 14 }
];

let ar2 = [{ id: 13, itemId: 1 },
    { id: 12, itemId: 14 }
];

let checkCommonElements = function(arr1, arr2) {
    arr1.forEach((object1, index1) => {
    	let flag = false;
        arr2.forEach((object2, index2) => {
            if (object1.itemId === object2.itemId) {
            	flag = true;
                console.log("Item present in ar2: ", JSON.stringify(object1));
            }
        });
        if(!flag) {
            console.log("Item not in ar2: ", JSON.stringify(object1));
        }
    });
}

checkCommonElements(ar1, ar2);