Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating array of length n with random numbers in JavaScript

Tags:

Following up on this answer for creating an array of specified length, I executed the below to get a corresponding result but filled with random numbers, instead of zeros.

var randoms = Array(4).fill(Math.floor(Math.random() * 9)); 

Well, mathematically speaking it's random, all right. But I'd like the randomness to be visible within the array and not only between runs, of course. Stupid computer... Don't do what I say. Do what I want!

I can iterate and put it my random (and varying) values. But I wonder, of pure curiosity, if it's possible to get the right result with a one-liner, like above, MatLab-style. Do I need to call eval(function()...)? I've heard a lot of bad things about eval...

Note that the above produces code like this:

[7, 7, 7, 7]
[3, 3, 3, 3]

etc. while I want something like

[1, 2, 3, 4]
[4, 3, 8, 4]

like image 824
Konrad Viltersten Avatar asked Jan 23 '16 17:01

Konrad Viltersten


People also ask

How do you create an array of N lengths?

To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.

How do you create an array of random values?

In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.


1 Answers

What does Array#fill do?

According to MDN

The fill() method fills all the elements of an array from a start index to an end index with a static value.

You can use Function#apply, Array#map, Math.floor(), Math.random().

In ES6, Array#from and Arrow function can be used.

Array.from({length: 6}, () => Math.floor(Math.random() * 9)); 

Array.apply(null, Array(6)).map(() => Math.floor(Math.random() * 9));

var randomArr = Array.from({length: 6}, () => Math.floor(Math.random() * 9));    document.getElementById('result').innerHTML = JSON.stringify(randomArr, 0, 4); // For demo only
<pre id="result"></pre>

In ES5:

Array.apply(null, Array(6)).map(function(item, index){     return Math.floor(Math.random() * 9); }); 

var randomArr = Array.apply(null, Array(6)).map(function(item, index){      return Math.floor(Math.random() * 9)  });    document.getElementById('result').innerHTML = JSON.stringify(randomArr, 0, 4);
<pre id="result"></pre>

What is Array.apply(null, Array(n))? Can new Array(n) used here?

Both the above code create new array of six elements, each element having value as undefined. However, when used new syntax, the created array is not iterable. To make the array iterable, Array.apply(null, Array(6)) syntax is used.


If you have lodash included on page, it's really easy.

_.times(6, _.random.bind(0, 100))         ^                        - Number of elements in array                          ^       - Random number range min                             ^^^  - Random number range max 

Note: This answer is inspired from Colin Toh's blog

like image 74
Tushar Avatar answered Oct 17 '22 18:10

Tushar