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?

2
  • 1
    For checking equality of two JS objects, refer this: stackoverflow.com/questions/201183/… Commented Feb 4, 2020 at 3:46
  • stringify is failing here because of generating different strings due to the different ordering of keys. Commented Feb 4, 2020 at 3:47

2 Answers 2

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]})
));

Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.