EN
TypeScript - generate array with 10 random numbers
0
points
In this article, we would like to show you how to generate an array with 10 random numbers in TypeScript.
Quick solution:
const array: number[] = Array(10) // array size is 10
.fill(undefined)
.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.
1. 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:
const array: number[] = Array(10) // array size is 10
.fill(undefined)
.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:
const array: number[] = Array(10) // array size is 10
.fill(undefined)
.map(() => Math.floor(50 * Math.random())); // numbers from 0-50 (exclusive)
console.log(array);