6

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

Ayaz Ali Shah
  • 3,453
  • 9
  • 36
  • 68

4 Answers4

7

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));
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
  • You means second time values will be unique and the first values will be remove from array correct ? – Ayaz Ali Shah Jun 12 '16 at 06:35
  • In `getThree` it is possible to return `['One', 'One', 'One']; in the second example, you won't ever re-use a number *in the same call.* Since it is creating a *copy* of the original array, the next time you call `getUnique` all of the numbers will be available. – Jeremy J Starcher Jun 12 '16 at 06:37
  • Yes, this is very good logic to get unique, thanks appreciated for sharing knowledge – Ayaz Ali Shah Jun 12 '16 at 06:42
  • @mplungjan Depending upon how many items one wants from the array, that can be painfully inefficient. Lets say you have an array of 10 items and you want 9 .. you do a LOT of looping until you get those 9 values. On the other hand, if you're looking for 3 out of a 1000, your chance of collision is much smaller. – Jeremy J Starcher Jun 12 '16 at 06:46
  • I tested @Mohammad answer function, sometime it is returning duplicated values. – Ayaz Ali Shah Jun 12 '16 at 06:47
  • I read your two functions as both being needed – mplungjan Jun 12 '16 at 07:56
2

You can try something like this:

Logic:

  • Create a temp array so it does not replace original value.
  • Calculate random number and use % array.length to find correct index.
  • Use array.splice(index, 1) to remove the element from temp array, so that it will not repeat.

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

function getRandomValues(arr, count){
  var result = [];
  var _tmp = arr.slice();
  for(var i = 0; i<count; i++){
    var index = Math.ceil(Math.random() * 10) % _tmp.length;
    result.push(_tmp.splice(index, 1)[0]);
  }
  return result;
}

console.log(getRandomValues(arrayNum, 3))
Rajesh
  • 24,354
  • 5
  • 48
  • 79
1

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);

If you want to select diffrent item, you need to checking selected item before inserting in new array.

var arrayNum = ['One', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];  
var selected = [];
for (var i = 0; i < 3; i++){
    rand();
}
console.log(selected);

function rand(){
    var ran = arrayNum[Math.floor(Math.random() * arrayNum.length)];  
    if (selected.indexOf(ran) == -1)
        selected.push(ran);
    else
         rand();
}
Mohammad
  • 21,175
  • 15
  • 55
  • 84
0

You can do something like this:

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

var singleRandom = [];

for (var i = 0; i < 3; i++) {

  singleRandom.push(Math.floor(Math.random() * arrayNum.length));

}

console.log(arrayNum[singleRandom[0]]);
console.log(arrayNum[singleRandom[1]]);
console.log(arrayNum[singleRandom[2]]);
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Rahul Arora
  • 4,503
  • 1
  • 16
  • 24