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 unique random values from an array using javascript? I will appreciate if someone guide me. Thank you
pop() function: This method is used to remove elements from the end of an array. shift() function: This method is used to remove elements from the start of an array. splice() function: This method is used to remove elements from the specific index of an array.
We can use the random number generator to pick a random item from an array. The following code snippet has an array of author names (strings). We can pick a random author by generating a random number that is less than the number of items in the array and use the random index to pick a random author name in the string.
To get a random element from an array use the Math. floor() and Math. random functions to get a random array index, e.g. arr[Math. floor(Math.
I am going to assume that you are asking how to get a NEW array made of three elements in your current array.
If you don'd mind the possibly of duplicates, you can do something simple like: getThree
below.
However, if you don't want values duplicated, you can use the getUnique
.
var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
function getThree() {
return [
arrayNum[Math.floor(Math.random() * arrayNum.length)],
arrayNum[Math.floor(Math.random() * arrayNum.length)],
arrayNum[Math.floor(Math.random() * arrayNum.length)]
];
}
function getUnique(count) {
// Make a copy of the array
var tmp = arrayNum.slice(arrayNum);
var ret = [];
for (var i = 0; i < count; i++) {
var index = Math.floor(Math.random() * tmp.length);
var removed = tmp.splice(index, 1);
// Since we are only removing one element
ret.push(removed[0]);
}
return ret;
}
console.log(getThree());
console.log("---");
console.log(getUnique(3));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With