JavaScript - generate array with 10 random numbers
In this article, we would like to show you how to generate array with 10 random numbers in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const array = Array(10) // array size is 10
.fill()
.map(() => 50 * Math.random()); // numbers from 0-50 (exclusive)
console.log(array);
Note:
Use
Math.floor()to get integers instead of float numbers. You can find practical examples in the sections below.
Using Array.fill() with map() method
In this example we take the following steps:
- Create an array with size
10, - Use
fill()method to fill thearraywith specified values, - use
map()method to callMath.random()to generate a random value for each element in thearray(from 0-50 exclusive).
Practical example:
// ONLINE-RUNNER:browser;
const array = Array(10) // array size is 10
.fill()
.map(() => 50 * Math.random()); // numbers from 0-50 (exclusive)
console.log(array);
If you want to receive integers instead of float numbers use Math.floor() method:
Practical example:
// ONLINE-RUNNER:browser;
const array = Array(10) // array size is 10
.fill()
.map(() => Math.floor(50 * Math.random())); // numbers from 0-50 (exclusive)
console.log(array);
Using Array.from() method (ES6+)
In this example, we use Array.from() method to create an array with size 10 and fill it with random numbers.
Practical example:
// ONLINE-RUNNER:browser;
// The solution for ES6+
const array = Array.from({ length: 10 }, () => Math.random() * 50);
console.log(array);
If you want to receive integers instead of float numbers use Math.floor() method:
Practical example:
// ONLINE-RUNNER:browser;
// The solution for ES6+
const array = Array.from({ length: 10 }, () => Math.floor(Math.random() * 50));
console.log(array);
Using crypto object
In this example, you can find solution that lets to randomize arrays using embedded crypto object.
Source code:
// ONLINE-RUNNER:browser;
const randomArray = (length, constructor = Uint32Array) => {
const array = new constructor(length);
return crypto.getRandomValues(array);
};
// Usage example:
console.log(randomArray(5, Uint8Array)); // also: Int8Array
console.log(randomArray(5, Uint16Array)); // also: Int16Array
console.log(randomArray(5, Uint32Array)); // also: Int32Array
console.log(randomArray(5, BigUint64Array)); // also: BigInt64Array
Note: the solution was intruduced in major web browsers in 2011-2014.