Inventory Update - undefined

Tell us what’s happening:

I don’t get what i do wrong but i get this error “TypeError: Cannot read property ‘1’ of undefined” though type of argo[i][1] is number

Your code so far


function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
let argo = Array.from(new Set(arr1.concat(arr2)));

  
   argo.sort((a,b) => a[1].localeCompare(b[1]));
   
   for (var i = 0; i < argo.length; i++){
       if(argo[i][1] === argo[i+1][1]){
           argo[i][0] + argo[i+1][0];
           delete argo[i+1];          }
   }
   
return argo;
}

// 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"]
];
console.log(newInv[0].indexOf(curInv[2][1]));
console.log(updateInventory(curInv, newInv));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36.

Challenge: Inventory Update

Link to the challenge:
https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/inventory-update

The problem is you are performing a delete operation on an array which replaces the target element with null. So, on the second iteration of the loop, argo[i] will be null, and so argo[i][1] will return an error. To delete an array element, you should use the splice array method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice.

2 Likes

Ok. If i change to:

for (var i = 0; i < argo.length; i++){
       if(argo[i][1] === argo[i+1][1]){
           argo[i][0] += argo[i+1][0];
           argo.splice(i+1,1);        
      }

i also got

"TypeError: Cannot read property '1' of undefined"

though if i delete +1 from first appearance of this i got the result though not appropriate

What happens on the last iteration of your loop? argo[i] is the last element, right? Then what value would argo[i + 1] have?

1 Like

Man, you are absolutely correct!
Now i’ve changed for loop requirement to:
i < argo.length - 1;

and it worked