Inventory Update need help pls

Inventory Update need help pls
0

#1

Hi guys!
Console shows me mistake “Cannot read property ‘1’ of undefined” on line " answ.splice(answ[k], 1);"
Can anyone explaine why?

Here is my code :

function updateInventory(arr1, arr2) {

var answ = arr1.concat(arr2).sort(function(a, b){
return a[1] > b[1];
});

for(var i=0; i<answ.length; i++){
var k = i + 1;
if(answ[i][1] == answ[k][1]) {

  answ[i][0] += answ[k][0];
  answ.splice(answ[k], 1); ??? Cannot read property '1' of undefined ???
} 

}

return answ;

}

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

In the loop, k is set as i + 1 per iteration, which you then use to access answ. But i can get as high as answ.length - 1 in the loop, which is the highest accessible index in answ. At this highest possible value of i, what is the value of k?


#3

I use “k” just to access next item in arrey, after your question I change line “for(var i=0; i<answ.length -1
; i++)”; and deleted "answ.splice(answ[k], 1);"
Now there is no any mistakes, but another problem - I need to delete double items in arrays )). Need to think. Thank you for reply.


#4

I’ve done it !

function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you’re fired!

arr1 = arr1.concat(arr2).sort(function(a, b){
return a[1] > b[1];
});

for(var i=0; i<arr1.length - 1; i++){

    if(arr1[i][1] == arr1[i+1][1]) {
   
        arr1[i][0] += arr1[i+1][0];
    } 

}

var result = [];

nextInput:
for (var k = 0; k < arr1.length; k++) {

  for (var j = 0; j < result.length; j++) { 
    
    if (result[j][1] == arr1[k][1]) continue nextInput; 
  }
  
  result.push(arr1[k]);
}

return result;

}