0

I am trying to return a random number from an array of numbers i.e. cardNumbertemp.

    function cardRandomiser(){
        randomCard = Math.floor(Math.random()*cardNumbertemp.length);
        for (var i = 0; i < cardNumbertemp.length; i++){
            if (randomCard === cardNumbertemp[i]){
                cardNumbertemp.splice(i,1);
                return randomCard;
            }
        }
    }

This function needs to return a single random number from the array (cardNumbertemp) then remove the number from the array. It works however sometimes it returns undefined.

Swet
  • 49
  • 1
  • 8
  • 2
    Where is `cardNumbertemp`? Anyway, `undefined` happens whenever `randomCard` value is not present in `cardNumbertemp`. – briosheje Jun 28 '19 at 10:21
  • You can make a recursion, if the returning output is undefined then call the function again. – Rupesh Jun 28 '19 at 11:06

2 Answers2

1

If you are looking to getting a random number, you can use the below code. You ideally need not splice unless you do not intend to have that number again.

var cardNumbertemp = [45, 78, 23, 89];

(function() {
  console.log(getRandom());
})();

function getRandom() {
  randomCard = Math.floor(Math.random() * cardNumbertemp.length);
  return cardNumbertemp[randomCard];
}
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
0
let cardNumbertemp = [45, 78, 23, 89];  

for(let i = 0; i < cardNumbertemp.length + i; i++){
    // will give you random number b/w 0 & (length of given array - 1)
    let randomIndex = Math.floor((Math.random() * cardNumbertemp.length));

    console.log(cardNumbertemp[randomIndex]); // output random array value
    cardNumbertemp.splice(randomIndex, 1); // maintain unique random value
}
Ashish Kumar
  • 401
  • 4
  • 11