Skip to content
Advertisement

Compare two arrays of objects (given the objects have same props, but not values)

Consider below two arrays of objects:

const arr1 = [
  {name: "name1", id: 1},
  {name: "name2", id: 2},
  {name: "name3", id: 3}
];

const arr2 = [
  {name: "name1", id: 1},
  {name: "name2", id: 4},
  {name: "name3", id: 3}
];

Comparison of these two objects must return false because there are values for prop id in arr2 that are missing in arr1 (namely id: 4).

At this point, the below attempt has been made:

arr1.every(i => i.id === arr2.map(z =>z.id));

NOTE: Suppose arr2 was:

const arr2 = [
    {name: "name1", id: 1},
    {name: "name3", id: 3}
];

The comparison must return true, since the id of every element in arr2 is found in arr1‘s elements.

Advertisement

Answer

You’re relaly close, but map is for mapping each element of the array to some new value, not for seeing if an element exists. You’d use some for that, and you’d want to reverse the arrays you’re calling every and some on:

const flag = arr2.every(element => arr1.some(({id}) => id === element.id));

That says: “Does every element of arr2 have at least one matching element in arr1 by id?”

Live Example:

const arr1 = [
    {name: "name1", id: 1},
    {name: "name2", id: 2},
    {name: "name3", id: 3}
];

const arr2 = [
    {name: "name1", id: 1},
    {name: "name2", id: 4},
    {name: "name3", id: 3}
];

const arr3 = [
    {name: "name1", id: 1},
    {name: "name3", id: 3}
];

const result1 = arr2.every(element => arr1.some(({id}) => id === element.id));
console.log("arr2 and arr1: " + result1);

const result2 = arr3.every(element => arr1.some(({id}) => id === element.id));
console.log("arr3 and arr1: " + result2);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement