1

I have two arrays:

const array1 = [
    { id: 1, name: 'John', score: 124 },
    { id: 2, name: 'Angie', score: 80 },
    { id: 3, name: 'Max', score: 56 }
]

const array2 = [
    { id: 5, name: 'Lisa', score: 78  },
    { id: 2, name: 'Angie', score: 80 }
]

JSON.stringify(array1) == JSON.stringify(array2) is not a solution, because arrays have different number of objects.

array1.some(item=> array2.includes(item)) doesnt't work too.

If there a solution?

2 Answers2

0

Here is a quick solution, maybe not the most performant.

  const array1 = [
    { id: 1, name: 'John', score: 124 },
    { id: 2, name: 'Angie', score: 80 },
    { id: 3, name: 'Max', score: 56 },
  ];

  const array2 = [
    { id: 5, name: 'Lisa', score: 78 },
    { id: 2, name: 'Angie', score: 80 },
  ];

  // Index will have -1 if there is no match, otherwise it'll have
  // the index of the first found match in array1.
  const index = array1.findIndex(array1Item => {

    // This will return the index if found, otherwise -1
    const match = array2.findIndex(array2Item => {
      // return array1Item.id === array2Item.id;
      return JSON.stringify(array1Item) === JSON.stringify(array2Item);
    });

    return match > -1;
  });

Instead of stringifying the entire object, if id is unique, you can just compare id as shown in the commented code.

Be advised this could have a complexity of O(n^2) where n is your array sizes. Big arrays may take a while.

Here is it running on PlayCode. It logs index as 1 because the first match is the second item in array1.

Diesel
  • 5,099
  • 7
  • 43
  • 81
0

What i would suggest is since your id is unique , so try the below :

const array1 = [
    { id: 1, name: 'John', score: 124 },
    { id: 2, name: 'Angie', score: 80 },
    { id: 3, name: 'Max', score: 56 }
]

const array2 = [
    { id: 5, name: 'Lisa', score: 78  },
    { id: 2, name: 'Angie', score: 80 }
]


var array2Id = {}
array2.forEach(function(obj){
    bIds[obj.id] = obj;
});

// Return all elements in A, unless in B
let check =  array1.filter(function(obj){
    return !(obj.id in array2Id);
});

console.log(check,'there')

if check is an empty array that means both are same otherwise it will give the different objects.

Hope it helps feel free for doubts

Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45