-1

I want to compare two Arrays of object and check the equality with the same properties but different sequences, for example

const array1 = [{id:1,name:'john'},{id:2,name:'wick'}];
const array2 = [{id:2,name:'wick'},{id:1,name:'john'}];

// How can I check if these arrays have the same objects
Usama Abdul Razzaq
  • 643
  • 2
  • 10
  • 19

1 Answers1

2

const array1 = [{
  id: 1,
  name: 'john'
}, {
  id: 2,
  name: 'wick'
}];
const array2 = [{
  id: 2,
  name: 'wick'
}, {
  id: 1,
  name: 'john'
}];
const array3 = [{
  id: 2,
  name: 'abc'
}, {
  id: 1,
  name: 'john'
}];


console.log('array1 matches array2? ', isMatched(array1, array2));

console.log('array3 matches array2? ',isMatched(array3, array2));

function isMatched(arr1, arr2) {
  //sort arrays
  arr1.sort((a, b) => a.id - b.id);
  arr2.sort((a, b) => a.id - b.id);

  return arr1.every((obj, i) =>
        Object.keys(obj).length === Object.keys(arr2[i]).length &&
        Object.keys(obj).every(prop => obj[prop] === arr2[i][prop])
      )
    }
Salwa A. Soliman
  • 695
  • 1
  • 3
  • 13