Get Random Sample Of Items From Array, Where Items (which Are Also Arrays) Have Things Totaling To X

- 1 answer

In an array such as:

const myList = [['hi'], ['hello', 'bye'], ['ok'], ['blue', 'green', 'purple'], ['big', 'small', 'medium', 'orange', 'sky', 'ground', 'earth'], ['king', 'queen'], ['desk']]

How can I get a random sample of items in the array, but the total should be determined by input variable size.

So if the size = 3, an array would be returned such as

[['desk'], ['king', 'queen']]

or maybe

[['blue', 'green', 'purple']]

or even

[['ok'], ['desk'], ['hi']]

If size is greater than the number of items in a flattened myList, then it should just return the maximum available items.

I haven't been able to figure this out, how can this be done?



I would suggest you to shuffle the array with a function like this one:

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;

  return array;

shuffled_arr = shuffle(shuffled_arr); // assign and shuffle the data to this arr

and then pull 1 element until it reaches the maximum limit.

var shuffled_arr = shuffle(myList); // to shuffle the data
var results_arr = [];
var maximum_len = 3;
var current_len = 0;

for (let i = 0; i < shuffled_arr.length; i++) 
    if(current_len == maximum_len) break;
    if(current_len + shuffled_arr[i].length  <= maximum_len)
        current_len+= shuffled_arr[i].length;

In the end you have the array results_arr containing the X random strings.

You can check my fiddle over here - Cheers.