javascript get n random elements from array

Solutions on MaxInterview for javascript get n random elements from array by the best coders in the world

showing results for - "javascript get n random elements from array"
Alex
02 Oct 2020
1// Shuffle array
2const shuffled = array.sort(() => 0.5 - Math.random());
3
4// Get sub-array of first n elements after shuffled
5let selected = shuffled.slice(0, n);
6
Jayne
27 Aug 2018
1function getRandom(arr, n) {
2    var result = new Array(n),
3        len = arr.length,
4        taken = new Array(len);
5    if (n > len)
6        throw new RangeError("getRandom: more elements taken than available");
7    while (n--) {
8        var x = Math.floor(Math.random() * len);
9        result[n] = arr[x in taken ? taken[x] : x];
10        taken[x] = --len in taken ? taken[len] : len;
11    }
12    return result;
13}
queries leading to this page
javascript get n random elements from arrayhow to pick a random element from an array in javascript without consecutive repeatjs random select number from arrayget 10 random itens from an array javascriptjavascript get n random items from arrayjs random select from arrayget random 4 elements from array javascriptchoose one number at random arrayjs get random 10 items from arrayjs get n random value from arrayselect random 5 element from array javascriptjavascript random choose from arraygenerate random slice of array javascriptjs choose n amount of random from arrayhow to make math random not repeat array index using an if statement javascriptjs get random n items from arrayget one random element from array javascriptjavascript select n random elements from an arrayjs random choice from arrayjs random n elements from array realpicking 3 random items from an array javascriptjs one line array with random amount of elementsget random x elements from an array jsjavascript random choice from arrayjavascript select n random element from an arrayarray math random return one itemselect random item from array javascriptwhile random value is n array javascriptget 3 random items from array javascriptjs random n from arrayget random 10 elements from array jsselect random element from array javascriptjavascript take take n random elements from arrayrandom 10 item arraypick n random elements from array javascriptget n random elements from array javascriptjavascript random selection from arrayhow to select random index from javascript array without repeatingselect five random items from array javascriptget n random items from array javascriptnodejs choose one item from array randomlyjavascript get n random elements from array