Need help to figure out whats wrong with my array iteration

Hi guys, if any of you could point out what’s my mistake will be a big help!

I’m not getting the output I’m expecting.

const ref = [100, 20, 10, 5];

const len = [1, 3, 2, 11];

var change = 96;

const output = [];

let n = 0;

for ( let i = 0; i < 4; i++ ) {
  if ( change > ref[i] )
  while ( n < len[i] ) {
    change = change - ref[i];
    output.push(ref[i]);
    n++;
  };
};

console.log(output) // [ 20, 20, 20, 5, 5, 5, 5, 5, 5, 5, 5 ]
console.log(change) // -4

Expecting,
output : [ 20, 20, 20, 10, 10, 5, 5, 5 ];
change : 1;

Cheers~

You need to reassign the value of n to 0 outside of while loop. Otherwise it’s value will keep on adding in each iteration in

above loop

1 Like

OMG thank you so much! I so over look at it. hahahaha