Inventory Update: Help please

Inventory Update: Help please
0

#1

I keep returning the array with any new items containing double the correct quantity. Can anyone take a look at my code and let me know why that is happening?


function updateInventory(arr1, arr2) {
    // All inventory must be accounted for or you're fired!
  var i;
  var j;
  var counter = 1;
  
  
  
  for (i=0; i<arr2.length; i++) {
    counter = 0;
    for (j=0; j<arr1.length; j++) {
      if (arr2[i][1] === arr1[j][1]) {
        arr1[j].splice(0,1,(arr1[j][0] + arr2[i][0]));
      }
      else if (arr2[i][1] != arr1[j][1]) {
        counter++;
        if (counter === arr1.length) {
        arr1.push(arr2[i]);
      }
      }
      
    }
  }
   
  return arr1.sort(function(a, b) {
   if (a[1] < b[1]) return -1;
   if (a[1] > b[1]) return 1;
   return 0;
 });
}

// 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);

#2

I have added some console.log statements to your code below, to give you a hint at what is causing it.

  for (i=0; i<arr2.length; i++) {
    counter = 0;
    for (j=0; j<arr1.length; j++) {
      console.log(arr2[i][1], arr1[j][1])
      if (arr2[i][1] === arr1[j][1]) {
        console.log('match', (arr1[j][0] + arr2[i][0]))
        arr1[j].splice(0,1,(arr1[j][0] + arr2[i][0]));
      }

#3

Thank you so much! I realized i was adding to the length of arr1 and so it then looped one more time.