2
var array = ["one", "two", "three", "four", "five"];
var item = array[Math.floor(Math.random()*array.length)];

The code above selects a random item from the array. However, how could I get it to select 3 random elements from the array at once, rather than only one.

Rather than only selecting three for example, it should be something like two five one.

gandreadis
  • 3,004
  • 2
  • 26
  • 38
  • Do you want them to be different? – Oriol Jan 01 '17 at 22:05
  • @Oriol Yes, I would like them to be different –  Jan 01 '17 at 22:06
  • first make an array to store selected items `var items=[]` then you can fill it in a loop, and as you select your item, also splice it from `array`, or you can use nested while loops, one checking if there's <3 elements in your items array, one checks if new item is already in it – d3vi4nt Jan 01 '17 at 22:10
  • Try adapting this answer: http://stackoverflow.com/a/3943985/145346 – Mottie Jan 01 '17 at 22:10

2 Answers2

8

You could use a dummy array for counting and a copy of the array and splice the random items without shuffling the array.

var array = ["one", "two", "three", "four", "five"],
    result = array.slice(0, 3).map(function () { 
        return this.splice(Math.floor(Math.random() * this.length), 1)[0];
    }, array.slice());

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

You can shuffle() the array and then get the first X items you need:

var array = ["one", "two", "three", "four", "five"];
var n = 3;
function shuffle(a) {
    for (let i = a.length; i; i--) {
        let j = Math.floor(Math.random() * i);
        [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
}
shuffle(array)
console.log(array.slice(0, 3))

The shuffle function was taken from this question: How can I shuffle an array?

If you still need the original array you can use slice it:

var array = ["one", "two", "three", "four", "five"];
var n = 3;
function shuffle(a) {
    for (let i = a.length; i; i--) {
        let j = Math.floor(Math.random() * i);
        [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
}
array_tmp = array.slice(0)
shuffle(array_tmp)
console.log(array_tmp.slice(0, 3))
console.log(array)
Community
  • 1
  • 1
Dekel
  • 60,707
  • 10
  • 101
  • 129