I have 2 arrays like this:
const arr1 = [
{id: 1, qty: 2, checked: true},
{id: 2, qty: 2, checked: true},
{id: 3, qty: 2, checked: false}
]
const arr2 = [
{id: 1, qty: 2},
{id: 2, qty: 2}
]
I want to copy values of arr1 to arr2 where checked is true only, more than that if arr1 value is already exist in arr2 I just want it to update its qty not duplicate again. But my problem is that in some scenarios I got it duplicate and update at the same time. Below here I try with for loops.
const handleAdd = () => {
let newArray = [...arr2]
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if(arr2[j].id === arr1[i].id && arr1[i].checked === true){
newArray[j].qty = newArray[j].qty + arr1[i].qty
break
}else{
if(arr1[i].checked === true){
newArray.push(arr1[i])
break
}
}
}
}
console.log(newArray)
}
What went wrong here, any solution? Thanks in advance