Search code examples
javascriptarrayscomparison

Comparing two arrays with objects with unordered keys


I know they're several questions that indicate how to do this, however, when the keys of the objects are in a different order the provided solutions do not work.

let array1 = [
  { name: 'David', age: 30 },
  { name: 'Amy', age: 39 }
];

let array2 = [
  { age: 30, name: 'David' },
  { age: 39, name: 'Amy' }
];

Comparing the arrays

console.log(array1.every((value, index) => {
   return JSON.stringify(value) === JSON.stringify(array2[index]);
})

// Returns false
// Expected true

Understandably these two arrays are different but the data is the same. So...

How do I compare arrays with objects in which I cannot guarantee that the keys are ordered identically?


Solution

  • You can do a proper object comparison, there are a lot of ways to do that.

    Here's one of the examples:

    let array1 = [
      { name: 'David', age: 30 },
      { name: 'Amy', age: 39 }
    ];
    
    let array2 = [
      { age: 30, name: 'David' },
      { age: 39, name: 'Amy' }
    ];
    
    console.log(array1.every((value, index) => 
      Object.keys(value).length === Object.keys(array2[index]).length &&
      JSON.stringify(value) === JSON.stringify({...value, ...array2[index]})
    ));