42

Possible Duplicate:
JavaScript: Getting random value from an array

var numbers = new Array('1','2','4','5','6','7','8','9','10');

I have a JavaScript Array and now want to randomly choose four different numbers from it and then express it on the page (through document.write). Obviously each time the page is reloaded by the user it would show four different random numbers.

Community
  • 1
  • 1
geef
  • 589
  • 1
  • 6
  • 8
  • 4
    OT: It is better practices to use array literals: `var numbers = ['1', ...];`. – Felix Kling Aug 23 '11 at 09:14
  • 10
    Actually this is not the same question as the supposed duplicate: getting more than one, different, properly random value from an array is significantly more complicated than just getting one random value. – Tim Down Aug 23 '11 at 22:55
  • @TimDown: Agreed. If this would be the same question as the supposed duplicate the answer(s) would be the same (same questions have same answers right?) which clearly are not. – Juan Jan 18 '13 at 03:02
  • The following is a closer duplicate: http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array – Tim Down Dec 10 '14 at 14:47

4 Answers4

57

You could shuffle the array and pick the first four.

numbers.sort( function() { return 0.5 - Math.random() } );

Now numbers[0], numbers[1]... and so on have random and unique elements.

Note that this method may not be an optimal way to shuffle an array: see Is it correct to use JavaScript Array.sort() method for shuffling? for discussion.

Community
  • 1
  • 1
JJJ
  • 32,902
  • 20
  • 89
  • 102
  • 2
    Nice one! Good point taking the unique-elements into account. – Jochem Aug 23 '11 at 09:17
  • 4
    It hardly matters in this circumstance, but I find it interesting all the same; this method turns out not-to-be-so-random after all: http://www.sitepoint.com/microsoft-fix-their-non-random-browser-choice-screen/ – Matt Aug 23 '11 at 09:18
  • @Matt Good point, I'll edit the answer. – JJJ Aug 23 '11 at 09:20
  • 3
    This also changes the original array, which may be undesirable. – Tim Down Aug 23 '11 at 10:01
  • Or `number.filter(() => Math.round(Math.random())` to get random items and continue with sort in case it's needed. – wintercounter May 04 '18 at 14:36
25

If you want this to be as random as the native implementations of JavaScript's Math.random() will allow, you could use something like the following, which also has the advantages of leaving the original array untouched and only randomizing as much of the array as required:

function getRandomArrayElements(arr, count) {
    var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}


var numbers = ['1','2','4','5','6','7','8','9','10'];
alert( getRandomArrayElements(numbers, 4) );
Tim Down
  • 318,141
  • 75
  • 454
  • 536
3
//return a random integer between 0 and 10

document.write(Math.floor(Math.random()*11));
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • 1
    I assumed that "four different numbers" means that the numbers have to be unique. – JJJ Aug 23 '11 at 09:15
  • Or `document.write( numbers[ (Math.floor(Math.random()*11) ] ] );` which becomes increasingly important if the numbers array doesn't contain something as trivial as 1-10. – Jochem Aug 23 '11 at 09:16
  • I didn't as it says everytime page is loaded it should be random. – NimChimpsky Aug 23 '11 at 09:16
  • @Nim Could be both ways, but I interpreted that part so that each page load should pull different (but unique) random numbers, not the sames that were shown the last time. – JJJ Aug 23 '11 at 09:18
3
var numbers = new Array('1','2','4','5','6','7','8','9','10');
document.write(numbers[Math.floor(Math.random()*numbers.length)]);
hungryMind
  • 6,931
  • 4
  • 29
  • 45