Categories
JavaScript Answers

How to Generate an Array of Random Numbers with JavaScript?

Spread the love

We can easily expand the code above to generate an array of random numbers. Using the Array.from method that we used above, we can create the array like in the following code:

const arr = Array.from({
  length: 10
}, (v, i) => {
  const min = 1;
  const max = 10;
  return Math.random() * (max - min) + min
});
console.log(arr)

In the second argument of the Array.from method call, we modified the function for mapping the values to the number generator function with the code inside it as the same code that we used to generate random numbers.

Again, we can specify the length property of the object in the first argument to the length of the array that we want. If we run the code above, the console.log output from the statement on the last line should log something like:

[2.09822597784169, 9.485219511793478, 4.905513590655689, 5.428402066955793, 5.874266428138649, 6.288415362686418, 2.768483595321933, 9.849179787675595, 1.1291148797430082, 6.725810669834928]

Also, we can use the integer generator code that we have before in the same manner, like in the code below:

const arr = Array.from({
  length: 10
}, (v, i) => {
  let min = 1;
  let max = 10;
  min = Math.ceil(min);
  max = Math.floor(max);
  return num = Math.floor(Math.random() * (max - min)) + min;
});
console.log(arr)

We have the same code that we used to generate integers as before, except that we used it to generate an array of random integers. If we run the code above, we should get something like the following:

[8, 3, 5, 4, 4, 9, 9, 1, 1, 1]

from the console.log statement above.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *