Trying to build an array that fills each position with a dice roll

Here is my current code:

const diceRoll = Math.trunc(Math.random() * 6) + 1;
const diceRollArr = Array.from ({length: 4}, (_, i) => diceRoll[i]);

console.log(diceRollArr); //Returns: (4)[undefined, undefined, undefined, undefined]

Can’t wrap my head around what I’m missing. If I do:

const diceRoll = Math.trunc(Math.random() * 6) + 1;
    const diceRollArr = Array.from ({length: 4}, (_, i) => diceRoll);

It will generate the same dice roll for the given array length, so I need a way to do a dice roll for each index position. Any help would be greatly appreciated, thanks!

>Solution :

You are accessing diceRoll as an array when it’s a variable. Also you need diceRoll to be a function and call it at every iteration

const diceRoll = () => Math.trunc(Math.random() * 6) + 1;
const diceRollArr = Array.from ({length: 4}, (_, i) => diceRoll(i));

console.log(diceRollArr);

Leave a Reply