Hendrik Hendrik - 1 year ago 70
Javascript Question

Random Selection from Array into new Array

I have seen this question answered here, but i have an "Add on" Question that is related.

Im trying to achieve:

the same but with the output being a selection of more than 1, the above works fine if you only want a single return...

How can I return (x) amount of outputs #7 in this case into a new var or array ...? Some guidance on best practice will also be appreciated ;)

Thanks a bunch....

Just for fun,

Create a teeny weenie web App that returns 7 variable numbers in a range [ 1 - 49 ] into an array.
Think return a list of Lotto Numbers
Create new array from selection using _underscore.js [Sample function]

**** I know this is easier, but im trying to get an understanding
of using Vanilla JS to accomplish this

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

var getLoot = Array.from(Array(50).keys()) // Create array of 49 numbers.
var pick = getLoot[Math.floor(Math.random() * getLoot.length)];


// pick returns a single which is fine if you want a single but, ..
// I want something like this :

var pick = function() {
// code that will return 7 numbers from the array into a new Array
// will randomize every time pick is called...

Answer Source

If you want to return more than just 1 value you can store your results into a data structure like an array. Here is a solution to the problem assuming you can pass in your array of 50 numbers into the pick() funciton.:

var getRandomArbitrary = function(min, max) {
    return Math.random() * (max - min) + min;

var pick = function(fiftyNumberArray, numberOfValuesWanted) {
    var randomNums = [];
    for(var i = 0; i < numberOfValuesWanted; i++) {
            fiftyNumberArray[getRandomArbitrary(0, 50)]
    return randomNums;

var fiftyNumbers = [] // <- set your array of fifty numbers
pick(fiftyNumbers, 7);

Javascript's Math.random() will return a value in between 0 and 1 (exclusive). So to get an index scaled up to the correct value to look into your array, you would want to multiply that by the formula (max - min) + min

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download