Create an array with random values Create an array with random values arrays arrays

Create an array with random values


The shortest approach (ES6)

// randomly generated N = 40 length array 0 <= A[N] <= 39Array.from({length: 40}, () => Math.floor(Math.random() * 40));

Enjoy!


Here's a solution that shuffles a list of unique numbers (no repeats, ever).

for (var a=[],i=0;i<40;++i) a[i]=i;// http://stackoverflow.com/questions/962802#962890function shuffle(array) {  var tmp, current, top = array.length;  if(top) while(--top) {    current = Math.floor(Math.random() * (top + 1));    tmp = array[current];    array[current] = array[top];    array[top] = tmp;  }  return array;}a = shuffle(a);

If you want to allow repeated values (which is not what the OP wanted) then look elsewhere. :)


ES5:

function randomArray(length, max) {    return Array.apply(null, Array(length)).map(function() {        return Math.round(Math.random() * max);    });}

ES6:

randomArray = (length, max) => [...new Array(length)]    .map(() => Math.round(Math.random() * max));