-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 
6
  • Why do you not sort them previously to check the equality? Commented Nov 16, 2022 at 12:51
  • 1
    Check this post stackoverflow.com/q/6229197/7785337 Commented Nov 16, 2022 at 12:52
  • In my logic sorting is not required @ManuelMB Commented Nov 16, 2022 at 12:53
  • Does this answer your question? How to know if two arrays have the same values Commented Nov 16, 2022 at 12:53
  • These two answers are for non object data, I need to work with object data Commented Nov 16, 2022 at 12:57

1 Answer 1

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

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

2 Comments

can you define this line // a.id - b.id
a & b refer to array elements (elements here are objects so, I try to sort them according to id property) .. same as sorting array of numbers arr.sort((a, b)=> a-b)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.