Get random array from array javascript

Just two lines :

// Shuffle array
const shuffled = array.sort(() => 0.5 - Math.random());

// Get sub-array of first n elements after shuffled
let selected = shuffled.slice(0, n);

DEMO:

answered Jul 25, 2016 at 14:57

Get random array from array javascript

Abdennour TOUMIAbdennour TOUMI

79.3k36 gold badges233 silver badges238 bronze badges

7

Try this non-destructive (and fast) function:

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
        throw new RangeError("getRandom: more elements taken than available");
    while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
    return result;
}

Get random array from array javascript

answered Oct 9, 2013 at 10:52

13

There is a one-liner unique solution here

 array.sort(() => Math.random() - Math.random()).slice(0, n)

answered Sep 27, 2019 at 2:26

Get random array from array javascript

Olalekan SogunleOlalekan Sogunle

2,2391 gold badge19 silver badges26 bronze badges

2

lodash _.sample and _.sampleSize.

Gets one or n random elements at unique keys from collection up to the size of collection.

_.sample([1, 2, 3, 4]);
// => 2

_.sampleSize([1, 2, 3], 2);
// => [3, 1]
 
_.sampleSize([1, 2, 3], 3);
// => [2, 3, 1]

Get random array from array javascript

genericUser

2,0121 gold badge15 silver badges29 bronze badges

answered Apr 9, 2020 at 3:04

nodejhnodejh

7,7581 gold badge18 silver badges23 bronze badges

2

Getting 5 random items without changing the original array:

const n = 5;
const sample = items
  .map(x => ({ x, r: Math.random() }))
  .sort((a, b) => a.r - b.r)
  .map(a => a.x)
  .slice(0, n);

(Don't use this for big lists)

answered Mar 25, 2018 at 19:12

Get random array from array javascript

pomberpomber

21.7k10 gold badges75 silver badges91 bronze badges

2

create a funcion which does that:

var getMeRandomElements = function(sourceArray, neededElements) {
    var result = [];
    for (var i = 0; i < neededElements; i++) {
        result.push(sourceArray[Math.floor(Math.random()*sourceArray.length)]);
    }
    return result;
}

you should also check if the sourceArray has enough elements to be returned. and if you want unique elements returned, you should remove selected element from the sourceArray.

answered Oct 9, 2013 at 10:37

Get random array from array javascript

2

Porting .sample from the Python standard library:

function sample(population, k){
    /*
        Chooses k unique random elements from a population sequence or set.

        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).

        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.

        To choose a sample in a range of integers, use range as an argument.
        This is especially fast and space efficient for sampling from a
        large population:   sample(range(10000000), 60)

        Sampling without replacement entails tracking either potential
        selections (the pool) in a list or previous selections in a set.

        When the number of selections is small compared to the
        population, then tracking selections is efficient, requiring
        only a small set and an occasional reselection.  For
        a larger number of selections, the pool tracking method is
        preferred since the list takes less space than the
        set and it doesn't suffer from frequent reselections.
    */

    if(!Array.isArray(population))
        throw new TypeError("Population must be an array.");
    var n = population.length;
    if(k < 0 || k > n)
        throw new RangeError("Sample larger than population or is negative");

    var result = new Array(k);
    var setsize = 21;   // size of a small set minus size of an empty list

    if(k > 5)
        setsize += Math.pow(4, Math.ceil(Math.log(k * 3) / Math.log(4)))

    if(n <= setsize){
        // An n-length list is smaller than a k-length set
        var pool = population.slice();
        for(var i = 0; i < k; i++){          // invariant:  non-selected at [0,n-i)
            var j = Math.random() * (n - i) | 0;
            result[i] = pool[j];
            pool[j] = pool[n - i - 1];       // move non-selected item into vacancy
        }
    }else{
        var selected = new Set();
        for(var i = 0; i < k; i++){
            var j = Math.random() * n | 0;
            while(selected.has(j)){
                j = Math.random() * n | 0;
            }
            selected.add(j);
            result[i] = population[j];
        }
    }

    return result;
}

Implementation ported from Lib/random.py.

Notes:

  • setsize is set based on characteristics in Python for efficiency. Although it has not been adjusted for JavaScript, the algorithm will still function as expected.
  • Some other answers described in this page are not safe according to the ECMAScript specification due to the misuse of Array.prototype.sort. This algorithm however is guaranteed to terminate in finite time.
  • For older browsers that do not have Set implemented, the set can be replaced with an Array and .has(j) replaced with .indexOf(j) > -1.

Performance against the accepted answer:

  • Get random array from array javascript
  • https://jsperf.com/pick-random-elements-from-an-array
  • The performance difference is the greatest on Safari.

user

20.7k9 gold badges109 silver badges98 bronze badges

answered Aug 7, 2017 at 22:55

Get random array from array javascript

Derek 朕會功夫Derek 朕會功夫

89.6k41 gold badges177 silver badges242 bronze badges

1

If you want to randomly get items from the array in a loop without repetitions you can remove the selected item from the array with splice:

var items = [1, 2, 3, 4, 5];
var newItems = [];

for (var i = 0; i < 3; i++) {
  var idx = Math.floor(Math.random() * items.length);
  newItems.push(items[idx]);
  items.splice(idx, 1);
}

console.log(newItems);

answered Oct 9, 2013 at 10:41

Rory McCrossanRory McCrossan

324k37 gold badges295 silver badges324 bronze badges

2

ES6 syntax

const pickRandom = (arr,count) => {
  let _arr = [...arr];
  return[...Array(count)].map( ()=> _arr.splice(Math.floor(Math.random() * _arr.length), 1)[0] ); 
}

answered Mar 27, 2019 at 9:58

Yair LevyYair Levy

1,04713 silver badges11 bronze badges

1

I can't believe that no one didn't mention this method, pretty clean and straightforward.

const getRnd = (a, n) => new Array(n).fill(null).map(() => a[Math.floor(Math.random() * a.length)]);

answered Feb 13, 2020 at 21:13

Get random array from array javascript

DedaDevDedaDev

3,3191 gold badge17 silver badges26 bronze badges

3

Array.prototype.getnkill = function() {
    var a = Math.floor(Math.random()*this.length);
    var dead = this[a];
    this.splice(a,1);
    return dead;
}

//.getnkill() removes element in the array 
//so if you like you can keep a copy of the array first:

//var original= items.slice(0); 


var item = items.getnkill();

var anotheritem = items.getnkill();

answered Oct 9, 2013 at 10:47

Get random array from array javascript

0

Here's a nicely typed version. It doesn't fail. Returns a shuffled array if sample size is larger than original array's length.

function sampleArr(arr: T[], size: number): T[] {
  const setOfIndexes = new Set();
  while (setOfIndexes.size < size && setOfIndexes.size < arr.length) {
    setOfIndexes.add(randomIntFromInterval(0, arr.length - 1));
  }
  return Array.from(setOfIndexes.values()).map(i => arr[i]);
}

const randomIntFromInterval = (min: number, max: number): number =>
  Math.floor(Math.random() * (max - min + 1) + min);

answered Jul 20, 2019 at 12:52

Get random array from array javascript

In this answer, I want to share with you the test that I have to know the best method that gives equal chances for all elements to have random subarray.

Method 01

array.sort(() => Math.random() - Math.random()).slice(0, n)

using this method, some elements have higher chances comparing with others.

calculateProbability = function(number=0 ,iterations=10000,arraySize=100) { 
let occ = 0 
for (let index = 0; index < iterations; index++) {
   const myArray= Array.from(Array(arraySize).keys()) //=> [0, 1, 2, 3, 4, ... arraySize]
   
  /** Wrong Method */
    const arr = myArray.sort(function() {
     return val= .5 - Math.random();
      });
     
  if(arr[0]===number) {
    occ ++
    }

    
}

console.log("Probability of ",number, " = ",occ*100 /iterations,"%")

}

calculateProbability(0)
calculateProbability(0)
calculateProbability(0)
calculateProbability(50)
calculateProbability(50)
calculateProbability(50)
calculateProbability(25)
calculateProbability(25)
calculateProbability(25)

Method 2

Using this method, the elements have the same probability:

 const arr = myArray
      .map((a) => ({sort: Math.random(), value: a}))
      .sort((a, b) => a.sort - b.sort)
      .map((a) => a.value)

calculateProbability = function(number=0 ,iterations=10000,arraySize=100) { 
let occ = 0 
for (let index = 0; index < iterations; index++) {
   const myArray= Array.from(Array(arraySize).keys()) //=> [0, 1, 2, 3, 4, ... arraySize]
   

  /** Correct Method */
  const arr = myArray
  .map((a) => ({sort: Math.random(), value: a}))
  .sort((a, b) => a.sort - b.sort)
  .map((a) => a.value)
    
  if(arr[0]===number) {
    occ ++
    }

    
}

console.log("Probability of ",number, " = ",occ*100 /iterations,"%")

}

calculateProbability(0)
calculateProbability(0)
calculateProbability(0)
calculateProbability(50)
calculateProbability(50)
calculateProbability(50)
calculateProbability(25)
calculateProbability(25)
calculateProbability(25)

The correct answer is posted in in the following link: https://stackoverflow.com/a/46545530/3811640

answered Dec 3, 2019 at 13:23

Get random array from array javascript

haouarinhaouarin

1,3319 silver badges8 bronze badges

2020
non destructive functional programing style, working in a immutable context.

const _randomslice = (ar, size) => {
  let new_ar = [...ar];
  new_ar.splice(Math.floor(Math.random()*ar.length),1);
  return ar.length <= (size+1) ? new_ar : _randomslice(new_ar, size);
}


console.log(_randomslice([1,2,3,4,5],2));

answered Oct 4, 2020 at 10:24

3

EDIT: This solution is slower than others presented here (which splice the source array) if you want to get only a few elements. The speed of this solution depends only on the number of elements in the original array, while the speed of the splicing solution depends on the number of elements required in the output array.

If you want non-repeating random elements, you can shuffle your array then get only as many as you want:

function shuffle(array) {
    var counter = array.length, temp, index;

    // While there are elements in the array
    while (counter--) {
        // Pick a random index
        index = (Math.random() * counter) | 0;

        // And swap the last element with it
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

var arr = [0,1,2,3,4,5,7,8,9];

var randoms = shuffle(arr.slice(0)); // array is cloned so it won't be destroyed
randoms.length = 4; // get 4 random elements

DEMO: http://jsbin.com/UHUHuqi/1/edit

Shuffle function taken from here: https://stackoverflow.com/a/6274398/1669279

answered Oct 9, 2013 at 10:40

TibosTibos

27.1k4 gold badges47 silver badges62 bronze badges

6

I needed a function to solve this kind of issue so I'm sharing it here.

    const getRandomItem = function(arr) {
        return arr[Math.floor(Math.random() * arr.length)];
    }

    // original array
    let arr = [4, 3, 1, 6, 9, 8, 5];

    // number of random elements to get from arr
    let n = 4;

    let count = 0;
    // new array to push random item in
    let randomItems = []
    do {
        let item = getRandomItem(arr);
        randomItems.push(item);
        // update the original array and remove the recently pushed item
        arr.splice(arr.indexOf(item), 1);
        count++;
    } while(count < n);

    console.log(randomItems);
    console.log(arr);

Note: if n = arr.length then basically you're shuffling the array arr and randomItems returns that shuffled array.

Demo

answered Feb 26, 2019 at 16:12

Get random array from array javascript

Storage LenovoStorage Lenovo

851 gold badge1 silver badge6 bronze badges

Here's an optimized version of the code ported from Python by @Derek, with the added destructive (in-place) option that makes it the fastest algorithm possible if you can go with it. Otherwise it either makes a full copy or, for a small number of items requested from a large array, switches to a selection-based algorithm.

// Chooses k unique random elements from pool.
function sample(pool, k, destructive) {
    var n = pool.length;
    
    if (k < 0 || k > n)
        throw new RangeError("Sample larger than population or is negative");
    
    if (destructive || n <= (k <= 5 ? 21 : 21 + Math.pow(4, Math.ceil(Math.log(k*3) / Math.log(4))))) {
        if (!destructive)
            pool = Array.prototype.slice.call(pool);
        for (var i = 0; i < k; i++) { // invariant: non-selected at [i,n)
            var j = i + Math.random() * (n - i) | 0;
            var x = pool[i];
            pool[i] = pool[j];
            pool[j] = x;
        }
        pool.length = k; // truncate
        return pool;
    } else {
        var selected = new Set();
        while (selected.add(Math.random() * n | 0).size < k) {}
        return Array.prototype.map.call(selected, i => pool[i]);
    }
}

In comparison to Derek's implementation, the first algorithm is much faster in Firefox while being a bit slower in Chrome, although now it has the destructive option - the most performant one. The second algorithm is simply 5-15% faster. I try not to give any concrete numbers since they vary depending on k and n and probably won't mean anything in the future with the new browser versions.

The heuristic that makes the choice between algorithms originates from Python code. I've left it as is, although it sometimes selects the slower one. It should be optimized for JS, but it's a complex task since the performance of corner cases is browser- and their version-dependent. For example, when you try to select 20 out of 1000 or 1050, it will switch to the first or the second algorithm accordingly. In this case the first one runs 2x faster than the second one in Chrome 80 but 3x slower in Firefox 74.

answered Apr 7, 2020 at 10:46

useruser

20.7k9 gold badges109 silver badges98 bronze badges

3

Sampling with possible duplicates:

const sample_with_duplicates = Array(sample_size).fill().map(() => items[~~(Math.random() * items.length)])

Sampling without duplicates:

const sample_without_duplicates = [...Array(items.length).keys()].sort(() => 0.5 - Math.random()).slice(0, sample_size).map(index => items[index]);

Since without duplicates requires sorting the whole index array first, it is considerably slow than with possible duplicates for big items input arrays.

Obviously, the max size of without duplicates is <= items.length

Check this fiddle: https://jsfiddle.net/doleron/5zw2vequ/30/

answered Jan 31 at 6:25

Get random array from array javascript

DulorenDuloren

2,1131 gold badge22 silver badges30 bronze badges

1

It extracts random elements from srcArray one by one while it get's enough or there is no more elements in srcArray left for extracting. Fast and reliable.

function getNRandomValuesFromArray(srcArr, n) {
    // making copy to do not affect original srcArray
    srcArr = srcArr.slice();
    resultArr = [];
    // while srcArray isn't empty AND we didn't enough random elements
    while (srcArr.length && resultArr.length < n) {
        // remove one element from random position and add this element to the result array
        resultArr = resultArr.concat( // merge arrays
            srcArr.splice( // extract one random element
                Math.floor(Math.random() * srcArr.length),
                1
            )
        );
    }

    return resultArr;
}

answered Aug 30, 2018 at 17:46

Get random array from array javascript

1

Here's a function I use that allows you to easily sample an array with or without replacement:

  // Returns a random sample (either with or without replacement) from an array
  const randomSample = (arr, k, withReplacement = false) => {
    let sample;
    if (withReplacement === true) {  // sample with replacement
      sample = Array.from({length: k}, () => arr[Math.floor(Math.random() *  arr.length)]);
    } else { // sample without replacement
      if (k > arr.length) {
        throw new RangeError('Sample size must be less than or equal to array length         when sampling without replacement.')
      }
      sample = arr.map(a => [a, Math.random()]).sort((a, b) => {
        return a[1] < b[1] ? -1 : 1;}).slice(0, k).map(a => a[0]); 
      };
    return sample;
  };

Using it is simple:

Without Replacement (default behavior)

randomSample([1, 2, 3], 2) may return [2, 1]

With Replacement

randomSample([1, 2, 3, 4, 5, 6], 4) may return [2, 3, 3, 2]

answered Jul 27, 2019 at 8:37

Jared WilberJared Wilber

5,13329 silver badges34 bronze badges

var getRandomElements = function(sourceArray, requiredLength) {
    var result = [];
    while(result.length

answered Sep 16, 2019 at 7:04

Get random array from array javascript

Manoj RanaManoj Rana

2,5081 gold badge23 silver badges26 bronze badges

const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 1, 2, 3, 4, 5];

const fetchRandomArray = ({pool=[], limit=1})=>{
let query = []
let selectedIndices = {}

while(query.length < limit){
    const index = Math.floor(Math.random()*pool.length)
    if(typeof(selectedIndices[index])==='undefined'){
        query.push(items[index])
        selectedIndices[index] = index
    }
}

console.log(fetchRandomArray({pool:items, limit:10})

answered Aug 13 at 10:03

Get random array from array javascript

1

Here is the most correct answer and it will give you Random + Unique elements.

function randomize(array, n)
{
    var final = [];
    array = array.filter(function(elem, index, self) {
        return index == self.indexOf(elem);
    }).sort(function() { return 0.5 - Math.random() });

    var len = array.length,
    n = n > len ? len : n;

    for(var i = 0; i < n; i ++)
    {
        final[i] = array[i];
    }

    return final;
}

// randomize([1,2,3,4,5,3,2], 4);
// Result: [1, 2, 3, 5] // Something like this

answered Dec 26, 2016 at 11:10

2

items.sort(() => (Math.random() > 0.5 ? 1 : -1)).slice(0, count);

answered Dec 27, 2019 at 15:38

Get random array from array javascript

1

2019

This is same as Laurynas Mališauskas answer, just that the elements are unique (no duplicates).

var getMeRandomElements = function(sourceArray, neededElements) {
    var result = [];
    for (var i = 0; i < neededElements; i++) {
    var index = Math.floor(Math.random() * sourceArray.length);
        result.push(sourceArray[index]);
        sourceArray.splice(index, 1);
    }
    return result;
}

Now to answer original question "How to get multiple random elements by jQuery", here you go:

var getMeRandomElements = function(sourceArray, neededElements) {
    var result = [];
    for (var i = 0; i < neededElements; i++) {
    var index = Math.floor(Math.random() * sourceArray.length);
        result.push(sourceArray[index]);
        sourceArray.splice(index, 1);
    }
    return result;
}

var $set = $('.someClass');// <<<<< change this please

var allIndexes = [];
for(var i = 0; i < $set.length; ++i) {
    allIndexes.push(i);
}

var totalRandom = 4;// <<<<< change this please
var randomIndexes = getMeRandomElements(allIndexes, totalRandom);

var $randomElements = null;
for(var i = 0; i < randomIndexes.length; ++i) {
    var randomIndex = randomIndexes[i];
    if($randomElements === null) {
        $randomElements = $set.eq(randomIndex);
    } else {
        $randomElements.add($set.eq(randomIndex));
    }
}

// $randomElements is ready
$randomElements.css('backgroundColor', 'red');

answered Feb 17, 2019 at 12:27

Get random array from array javascript

evilReikoevilReiko

18.4k24 gold badges82 silver badges99 bronze badges

2

Not the answer you're looking for? Browse other questions tagged javascript jquery html arrays or ask your own question.

How do you get random elements from an array?

To get multiple random elements from an array, use the sort() method on the array to shuffle the array elements in a random order, e.g. arr. sort(() => 0.5 - Math. random()) . Then call the slice() method on the shuffled array to get multiple random elements.

How do you shuffle an array?

There are two ways to shuffle an array in Java..
Collections.shuffle() Method..
Random Class..

What does math random () do?

The Math. random() function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range.

How do you generate a random number in Javascript?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.