โจทย์
มี 2 arrays ของ objects เก็บข้อมูลสินค้า ต้อง merge arrays โดย objects ที่มี id เดียวกันไม่ซ้ำ และ quantity ของ id ซ้ำจะรวมกัน
ตัวอย่างโค้ด
const first = [
{ id: "57e7a1cd6a3f3669dc03db58", quantity:3 },
{ id: "57e77b06e0566d496b51fed5", quantity:3 },
{ id: "57e7a1cd6a3f3669dc03db58", quantity:3 },
{ id: "57e77b06e0566d496b51fed5", quantity:3 }
];
const second = [
{ id: "57e7a1cd6a3f3669dc03db58", quantity:6 },
{ id: "57e77b06e0566d496b51fed5", quantity:6 }
];
const mergeArray = (first, second) => {
return [...first, ...second].reduce((acc, val, i, arr) => {
const { id, quantity } = val;
const ind = acc.findIndex(el => el.id === id);
if(ind !== -1){
acc[ind].quantity += quantity;
}else{
acc.push({ id, quantity });
}
return acc;
}, []);
}
console.log(mergeArray(first, second));
ผลลัพธ์
[
{ id: '57e7a1cd6a3f3669dc03db58', quantity: 12 },
{ id: '57e77b06e0566d496b51fed5', quantity: 12 }
]
คำอธิบาย
ใช้ spread operator รวม 2 arrays แล้ว reduce สร้าง array ใหม่ ตรวจสอบด้วย findIndex ว่ามี id นี้อยู่แล้วหรือไม่ ถ้ามีบวก quantity ถ้าไม่มี push object ใหม่เข้าไป