Get random subset of array javascript

In my opinion, I do not think shuffling the entire deck necessary. You just need to make sure your sample is random not your deck. What you can do, is select the size amount from the front then swap each one in the sampling array with another position in it. So, if you allow replacement you get more and more shuffled.

function getRandom(length) { return Math.floor(Math.random()*(length)); }

function getRandomSample(array, size) {
    var length = array.length;

    for(var i = size; i--;) {
        var index = getRandom(length);
        var temp = array[index];
        array[index] = array[i];
        array[i] = temp;
    }

    return array.slice(0, size);
}

This algorithm is only 2*size steps, if you include the slice method, to select the random sample.


More Random

To make the sample more random, we can randomly select the starting point of the sample. But it is a little more expensive to get the sample.

function getRandomSample(array, size) {
    var length = array.length, start = getRandom(length);

    for(var i = size; i--;) {
        var index = (start + i)%length, rindex = getRandom(length);
        var temp = array[rindex];
        array[rindex] = array[index];
        array[index] = temp;
    }
    var end = start + size, sample = array.slice(start, end);
    if(end > length)
        sample = sample.concat(array.slice(0, end - length));
    return sample;
}

What makes this more random is the fact that when you always just shuffling the front items you tend to not get them very often in the sample if the sampling array is large and the sample is small. This would not be a problem if the array was not supposed to always be the same. So, what this method does is change up this position where the shuffled region starts.


No Replacement

To not have to copy the sampling array and not worry about replacement, you can do the following but it does give you 3*size vs the 2*size.

function getRandomSample(array, size) {
    var length = array.length, swaps = [], i = size, temp;

    while(i--) {
        var rindex = getRandom(length);
        temp = array[rindex];
        array[rindex] = array[i];
        array[i] = temp;
        swaps.push({ from: i, to: rindex });
    }

    var sample = array.slice(0, size);

    // Put everything back.
    i = size;
    while(i--) {
         var pop = swaps.pop();
         temp = array[pop.from];
         array[pop.from] = array[pop.to];
         array[pop.to] = temp;
    }

    return sample;
}

No Replacement and More Random

To apply the algorithm that gave a little bit more random samples to the no replacement function:

function getRandomSample(array, size) {
    var length = array.length, start = getRandom(length),
        swaps = [], i = size, temp;

    while(i--) {
        var index = (start + i)%length, rindex = getRandom(length);
        temp = array[rindex];
        array[rindex] = array[index];
        array[index] = temp;
        swaps.push({ from: index, to: rindex });
    }

    var end = start + size, sample = array.slice(start, end);
    if(end > length)
        sample = sample.concat(array.slice(0, end - length));

    // Put everything back.
    i = size;
    while(i--) {
         var pop = swaps.pop();
         temp = array[pop.from];
         array[pop.from] = array[pop.to];
         array[pop.to] = temp;
    }

    return sample;
}

Faster...

Like all of these post, this uses the Fisher-Yates Shuffle. But, I removed the over head of copying the array.

function getRandomSample(array, size) {
    var r, i = array.length, end = i - size, temp, swaps = getRandomSample.swaps;

    while (i-- > end) {
        r = getRandom(i + 1);
        temp = array[r];
        array[r] = array[i];
        array[i] = temp;
        swaps.push(i);
        swaps.push(r);
    }

    var sample = array.slice(end);

    while(size--) {
        i = swaps.pop();
        r = swaps.pop();
        temp = array[i];
        array[i] = array[r];
        array[r] = temp;
    }

    return sample;
}
getRandomSample.swaps = [];

Last update on August 19 2022 21:51:52 (UTC/GMT +8 hours)

JavaScript Array: Exercise-35 with Solution

Write a JavaScript function to get a random item from an array.

Pictorial Presentation:

Get random subset of array javascript

Sample Solution:

HTML Code:




  
  JavaScript function to get a random item from an array.






JavaScript Code:

function random_item(items)
{
  
return items[Math.floor(Math.random()*items.length)];
     
}

var items = [254, 45, 212, 365, 2543];
console.log(random_item(items));

Sample Output:

365

Flowchart:

Get random subset of array javascript

ES6 Version:

function random_item(items)
{
  
return items[Math.floor(Math.random()*items.length)];
     
}

const items = [254, 45, 212, 365, 2543];
console.log(random_item(items));

Live Demo:

See the Pen JavaScript - Get a random item from an array - array-ex- 35 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get nth largest element from an unsorted array.
Next: Write a JavaScript function to create a specified number of elements and pre-filled numeric value array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

JavaScript: Tips of the Day

Delete operator

const name = 'Owen';
age = 21;

console.log(delete name);
console.log(delete age);

The delete operator returns a boolean value: true on a successful deletion, else it'll return false. However, variables declared with the var, const or let keyword cannot be deleted using the delete operator.
The name variable was declared with a const keyword, so its deletion is not successful: false is returned. When we set age equal to 21, we actually added a property called age to the global object. You can successfully delete properties from objects this way, also the global object, so delete age returns true.

Ref: https://bit.ly/323Y0P6


  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation