Create an array with random values

Alexandra picture Alexandra · Apr 29, 2011 · Viewed 156.7k times · Source

How can I create an array with 40 elements, with random values from 0 to 39 ? Like

[4, 23, 7, 39, 19, 0, 9, 14, ...]

I tried using solutions from here:

http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm

but the array I get is very little randomized. It generates a lot of blocks of successive numbers...

Answer

simonbor picture simonbor · Mar 27, 2017

The shortest approach (ES6)

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

Enjoy!