2D Arrays are not created properly in FCC Code page

I’m trying to create a 2D array but the array is being replicated multiple times and yielding incorrect arrays.

1.I’m getting this error only while running the code in the project named: JavaScript Algorithms and Data Structures Projects: Cash Register

  1. This error doesn’t appear in any other places like on the firefox console or in other FCC projects code page

Here is the code

function checkCashRegister(price, cash, cid) {
  var change;
  // Here is your change, ma'am.
  var total=0 ;
var toReturn=cash-price;

 for(var a=0 ; a<cid.length;a++)
{
total=total+cid[a][1];

}



var cols=[];
var rows=cid.length;

for(var nj=0;nj<rows;nj++)
{cols[nj]=[];}



for(var b=0 ; b<cid.length;b++)
{
if(cid[b][0]=="PENNY"){cols[b][0]=.01;cols[b][1]=cid[b][1];} 
if(cid[b][0]=="NICKEL"){cols[b][0]=.05;cols[b][1]=cid[b][1];}
if(cid[b][0]=="DIME"){cols[b][0]=.1;cols[b][1]=cid[b][1];}
if(cid[b][0]=="QUARTER"){cols[b][0]=.25;cols[b][1]=cid[b][1];}
if(cid[b][0]=="ONE"){cols[b][0]=1;cols[b][1]=cid[b][1];}
if(cid[b][0]=="FIVE"){cols[b][0]=5;cols[b][1]=cid[b][1];}
if(cid[b][0]=="TEN"){cols[b][0]=10;cols[b][1]=cid[b][1];}
if(cid[b][0]=="TWENTY"){cols[b][0]=20;cols[b][1]=cid[b][1];}
if(cid[b][0]=="ONE HUNDRED"){cols[b][0]=100;cols[b][1]=cid[b][1];}
}

console.log(cols);
 
}


// 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(20, 500, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

What is the error you are encountering?


It’s not an error perse but rather a strange behaviour of 2D arrays.
Here is my console page.Maybe you can try the code out if it helps .

What is the behavior that you are finding strange? How is the result different than what you expected?

Well in other places when I give the console.log I only get one 2D array, but in this page alone I’m getting 9 2D arrays, can you please explain why my code is giving 9 2D arrays if I have made a mistake.

That’s because your function checkCashRegister is running several times and it prints to the console every time it runs. The function is getting called once from the last line in the code above, and each test also calls the function to make sure it’s returning correctly for different input values.

Oh Got it :blush: gosh my bad , thanks a tonne .

No problem. Happy coding!

1 Like