Inventory Update

Inventory Update
0

#1

Hello all, I am working on the Update inventory exercise but I seem to have hit a brick wall. It keeps throwing the exception: Cannot read property '1' of undefined even when I use Try...Catch around my splice method call. Here is my code…

function updateInventory(arr1, arr2) {
    // All inventory must be accounted for or you're fired!
    
    for(var i = 0; i < arr2.length; i++) {

      for(var j = 0; j < arr1.length; j++) {

        if (arr1[j].includes(arr2[i][1])) {
           arr1[j][0] += arr2[i][0];
        } else {
           arr1.push(arr2[i]);
        }

        arr2.splice(i, 1);
      }
    }
  
    return arr1;
}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

updateInventory(curInv, newInv);

I know the error is because of an attempt to splice an empty array, but it persist even with the use of try catch and break in an error scenario. Please what can I do to solve this?


#2

If you put the following after the 2nd for statement, you will see the error is because your code arr2[i][1] is trying to refer to a 2 dimensional array element, but it is an empty 1 dimensional array.

 for(var i = 0; i < arr2.length; i++) 
    for(var j = 0; j < arr1.length; j++) {
        console.log(arr2)
        console.log()