I have two array of objects with different key/value pair. I want to match these if it doesnt match then console log the unmatched object.
array1=[
{'mobile': '24pp'},
{'android': '30pp'},
{ 'ios': '23pp'}
]
array2=[
{'ios': '23pp'},
{'android': '30pp'},
{'mobile': '24pp'}
]
If we try to compare array1 and array2, it should return true
array3=[
{'ios': '23pp'},
{'android': '30pp'},
{'mobile': '30pp'}
]
If we try to compare array1 and array3, it should return false and return {mobile: '24pp'}
Here is my code example but it compares objects one to one but in my case it can be in any order.
const array1 = [{
'mobile': '24pp'
},
{
'android': '30pp'
},
{
'ios': '23pp'
}
]
const array2 = [{
'ios': '23pp'
},
{
'android': '30pp'
},
{
'mobile': '24pp'
}
]
const array3 = [{
'ios': '23pp'
},
{
'android': '30pp'
},
{
'mobile': '30pp'
}
]
function objectsMatch(obj1, obj2) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
// Iterate through the keys and compare their values
for (const key of keys1) {
if (obj1[key] !== obj2[key]) {
return false;
}
}
// If all key-value pairs match, return true
return true;
}
for (let i = 0; i < 4; i++) {
console.log('matched ' + objectsMatch(array1[i], array2[i]));
}
3
Answers
Don’t compare the corresponding indexes. For each object in one array, use
some()
to check if a matching object exists in the other array.Use
every()
to test if all elements in the array have a match in the other array.You could compare the length of the keys. If they are the same, you should then check every other object. This works for n-number of items.
Note: After the keys are determined to be the same length, you need to transform the sub-array of objects into one object.
Given that the arrays have the same keys just make an object from the first array and loop the second and check whether a value with the same key in the object is the same:
And a benchmark with 10 items: