The below code is supposed to:
1) go through the two arrays,
2) if an item exist in both arrays, add its value to the value of the similar item in the first array,
3) if the item is found in arr2 but not arr1, add the item to arr1. My code works as desired when both arrays have the same size, but this is what I get with arrays of different size.
Result:
[[42, "Bowling Ball"], [4, "Dirty Sock"], [2, "cat"], [6, "mugs"], [2, "Dirty Sock"], [3, "rags"]]
should be:
[[42, "Bowling Ball"], [4, "Dirty Sock"], [2, "cat"], [3, "rags"], [3, "mugs"]]
And here is my code:
function updateInventory(arr1, arr2) {
for (var i = 0; i < arr1.length; i++) {
for (var j = i; j < arr2.length; j++) {
if (arr1[i][1] === arr2[j][1]) {
arr1[i][0] += arr2[j][0];
}
if (arr1[i].indexOf(arr2[j][1]) === -1) {
arr1.push(arr2[j]);
}
if (arr2.length > arr1.length) {
arr1.push(arr2[arr2.length -1]);
}
else
break;
}
}
return arr1;
}
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[2, "cat"],
];
var newInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[3, "rags"],
[3, "mugs"]
];
updateInventory(curInv, newInv);
What is the issue here?