0

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?

dutterbutter
  • 157
  • 1
  • 3
  • 12
  • 1
    For checking equality of two JS objects, refer this: https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects – Ajay Dabas Feb 04 '20 at 03:46
  • `stringify` is failing here because of generating different strings due to the different ordering of keys. – Ajay Dabas Feb 04 '20 at 03:47

2 Answers2

2

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]})
));
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
0

1) Convert array of objects to array of strings
2) Compare both array of strings (one way is to do with reduce as below).

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

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


const isEqual = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false;
  }
  const toStr = ({ name, age }) => `${name}-${age}`;
  const a1 = Array.from(arr1, toStr);
  const a2 = Array.from(arr2, toStr);
  return a1.every(item => a2.includes(item));
};

console.log(isEqual(array1, array2));
Siva K V
  • 10,561
  • 2
  • 16
  • 29