Languages
[Edit]
EN

JavaScript - generate array with 10 random numbers

0 points
Created by:
Paris-Bateman
434

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.

1. Using Array.fill() with map() method

In this example we take the following steps:

  1. Create an array with size 10,
  2. Use fill() method to fill the array with specified values,
  3. use map() method to call Math.random() to generate a random value for each element in the array (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);

2. 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);

References

  1. Array.prototype.fill() - JavaScript | MDN 
  2. Array.prototype.map() - JavaScript | MDN
  3. Math.random() - JavaScript | MDN
  4. Math.floor() - JavaScript | MDN

Alternative titles

  1. JavaScript - create array with random values
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - generate array with 10 random numbers

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join