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]));
}
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.
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;
}
function compareArrays(a1, a2) {
if (a1.length != a2.length) {
return false;
}
return a1.every(el1 => {
return a2.some(el2 => objectsMatch(el1, el2));
});
}
const array1 = [{
'mobile': '24pp'
},
{
'android': '30pp'
},
{
'ios': '23pp'
}
]
const array2 = [{
'ios': '23pp'
},
{
'android': '30pp'
},
{
'mobile': '24pp'
}
]
const array3 = [{
'ios': '23pp'
},
{
'android': '30pp'
},
{
'mobile': '30pp'
}
]
console.log("Compare array1 and array2");
console.log(compareArrays(array1, array2));
console.log("Compare array1 and array3");
console.log(compareArrays(array1, array3));