Ad
Get Random Sample Of Items From Array, Where Items (which Are Also Arrays) Have Things Totaling To X
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?
Ad
Answer
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;
results_arr.push(shuffled_arr[i]);
}
}
In the end you have the array results_arr containing the X random strings.
You can check my fiddle over here - https://jsfiddle.net/2ds4vxqp/ Cheers.
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad