Chi Lee
Chi Lee

Reputation: 35

How to add one element multiple times to array at once

The function should display the number of coins corresponding to a certain value; i.e: input of 56 should display back [25, 25, 5, 1].

I'm having trouble: 1) displaying 2+ of the same coin in the array (I understand the Math function below is not used correctly) 2) removing any 0s from the array

Thanks for your help.

function getCoins(){
	let coins = [25, 10, 5, 1];
	    amount = prompt ("Enter an amount to convert into coins");
	    coinAmount = "";
					

	for (i = 0; i < coins.length; i++){
		if (amount % coins[i] >= 0){ 
			coinAmount +=  coins[i] * (Math.floor (amount/coins[i])) + ","; 
			amount = amount % coins[i];  	
			console.log (coinAmount)
		} 
	} 
}
		
getCoins()

Upvotes: 0

Views: 91

Answers (2)

Eddie
Eddie

Reputation: 26844

One option is to push the array and use join to display it.

You can concat the coinAmount to a new Array(NumberOfCouns) and fill it with the coin type.

function getCoins() {
  let coins = [25, 10, 5, 1];
  let amount = prompt("Enter an amount to convert into coins");
  let coinAmount = [];


  for (i = 0; i < coins.length; i++) {
    if (Math.floor(amount / coins[i]) > 0) {

      coinAmount = coinAmount.concat(new Array(Math.floor(amount / coins[i])).fill(coins[i]));
      amount = amount - (Math.floor(amount / coins[i]) * coins[i]);
    }
  }

  console.log(coinAmount.join())
}

getCoins();

Upvotes: 1

Charis Moutafidis
Charis Moutafidis

Reputation: 363

How about this?

function getCoins(){
    let coins = [25, 10, 5, 1];
        amount = prompt ("Enter an amount to convert into coins");
        coinAmount = "";


    for (i = 0; i < coins.length; i++){
        if (amount >= coins[i]){ 
            var integer = parseInt(amount/coins[i]);
            coinAmount +=  integer + ","; 
            amount -= integer*coins[i];     
            console.log (coinAmount);
        }
        else{
            coinAmount += "0,";
            console.log (coinAmount);
        }
    } 
}

getCoins()

for input 30:

1,
1,0,
1,0,1,
1,0,1,0,

Because we have 1 coin of value 25 and 1 coin of value 5

for input 25:

1,
1,0,
1,0,0,
1,0,0,0,

Upvotes: 0

Related Questions