Reputation: 17
I have 2 arrays (array1 and array2). I want to compare array1 and array2 by using 'id' as the key and want to create 2 resultant arrays out of array2.
const array1 = [{ id: 176770 }, { id: 176771 }, { id: 176820 }];
const array2 = [
{ id: 176770, classfication: "comeone", type: "typeee" },
{ id: 176771, classfication: "comeone1", type: "typeee1" },
{ id: 176820, classfication: "comeone2", type: "typeee2" },
{ id: 176670, classfication: "comeone", type: "typeee" },
{ id: 176761, classfication: "comeone1", type: "typeee1" },
{ id: 176845, classfication: "comeone2", type: "typeee2" },
];
Please help me out to create these 2 arrays.
Upvotes: 0
Views: 116
Reputation: 2742
You can loop over the second array and find
for an element with same id
in first array. If there is no element present in first array, then your first condition is satisfied (Store it in result1
). If the element exists in first array, your second condition is satisfied (Store it in result2
)
const array1 = [{ "id": 176770 }, { "id": 176771 }, { "id": 176820 }]
const array2 = [{ "id": 176770, "classfication": "comeone", "type": "typeee" }, { "id": 176771, "classfication": "comeone1", "type": "typeee1" }, { "id": 176820, "classfication": "comeone2", "type": "typeee2" }, { "id": 176670, "classfication": "comeone", "type": "typeee" }, { "id": 176761, "classfication": "comeone1", "type": "typeee1" }, { "id": 176845, "classfication": "comeone2", "type": "typeee2" }]
let result1 = []
let result2 = [];
for (let element of array2) {
let existingInFirst = array1.find(ele => ele.id == element.id);
if (!existingInFirst) {
result1.push(element)
}
else{
result2.push(element)
}
}
console.log(result1)
console.log(result2)
Upvotes: 1