Here are sample arrays:
const firstArray = [
{
name: "q",
age: 10,
size: "M",
},
{
name: "w",
age: 10,
size: "S",
},
{
name: "e",
age: 10,
size: "M",
},
];
const secondArray = [
{
name: "q",
age: 10,
size: "M",
},
{
name: "w",
age: 10,
size: "S",
},
{
name: "i",
age: 10,
size: "S",
},
{
name: "x",
age: 10,
size: "S",
},
];
The goal is to compare the first array (firstArray
) with the second one (secondArray
) based on specific properties - in this case, name
and size
.
If there is a match, the results should be stored in a new array. If not, they should be stored in another array, resulting in two separate arrays at the end.
This is what I have attempted so far:
for (let j = 0; j < secondArray.length; j++) {
for (let i = 0; i < firstArray.length; i++) {
const { name: name1, size: size1 } = firstArray[i];
const { name: name2, size: size2 } = secondArray[j];
if (name1 === name2 && size1 === size2) {
matchingArr.push(firstArray.splice(i, 1)[0]);
break;
} else {
nonMatchingArr.push(firstArray[i]);
}
}
}
Matched items are stored in matchingArr
:
[ { name: 'q', age: 10, size: 'M' }, { name: 'w', age: 10, size: 'S' } ]
Non-matching items are stored in nonMatchingArr
:
[ { name: 'e', age: 10, size: 'M' },
{ name: 'e', age: 10, size: 'M' } ]
Expected result in nonMatchingArr
:
[ { name: 'e', age: 10, size: 'M' } ]
I would appreciate any guidance or assistance on improving this logic.