Mr. Developer Mr. Developer - 5 months ago 24
jQuery Question

How do I select random values from an array in Javascript or Jquery?

I'm trying to show 3 random values from an array. Following script is returning only single item from javaScript array.

var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var singleRandom = arrayNum[Math.floor(Math.random() * arrayNum.length)];
alert(singleRandom);


But I want to show three random value from array
arrayNum
, can any one guide me is this possible to get 3 random values from an array using javascript? I will appreciate if someone guide me. Thanks

Answer

Use for() to iterating random select

var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];  

var selected = [];
for (var i = 0; i < 3; i++){
    selected[i] = arrayNum[Math.floor(Math.random() * arrayNum.length)];
}

console.log(selected);