Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 936
Ayaz Ali Shah Avatar asked Jun 12 '16 06:06

Ayaz Ali Shah


People also ask

Can you pop a specific element from array in Javascript?

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.

How do you select a random string from 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.

How do you randomly index an array?

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.


1 Answers

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));
like image 56
Jeremy J Starcher Avatar answered Sep 30 '22 20:09

Jeremy J Starcher