Cash Register issues

Cash Register issues
0

#1

Tell us what’s happening:
I don’t understand why This isn’t working. I’m trying to create a new array containing the second value in each sub array, but for some reason, it says the value of “1” is underfined, referring to arr.push(cid[i][1]); Why does this not work? I this an incorrect use of push?

Edit: most people I have come across seem to use reduce… I don’t understand how reduce works on sub arrays.

Your code so far


function checkCashRegister(price, cash, cid) {
  var change = cash - price;

var arr = [];

for(let i = 0;i < cid.length + 1; i++){
  arr.push(cid[i][1]);
}
console.log(arr);

}

// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]

checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS aarch64 11151.51.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.85 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register


#2

The last iteration of the loop is the problem, you are looping 1 more time than you should. The cid array doesn’t have an element to give you in the last iteration.


#3

In you if statement you use length + 1. As javascript is 0 indexed you go 1 step too far.
For example a list of length 1 has only the index 0.
With the + 1 you try to access indexes 0 and 1. The last index access fails as the list is already finished.