The following code aims to:
1) iterate through the two arrays,
2) if an item exists in both arrays, add its value to the value of the matching item in the first array,
3) if the item is found in arr2 but not in arr1, add the item to arr1. The code functions correctly when both arrays are the same size, but encounters issues when dealing with arrays of different sizes.
Current Result:
[[42, "Bowling Ball"], [4, "Dirty Sock"], [2, "cat"], [6, "mugs"], [2, "Dirty Sock"], [3, "rags"]]
Expected Result:
[[42, "Bowling Ball"], [4, "Dirty Sock"], [2, "cat"], [3, "rags"], [3, "mugs"]]
Here is the code snippet:
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 seems to be the issue in this code snippet?