Multiple ways to create Random Array in javascript
- Admin
- Sep 20, 2023
- Javascript
It is a short tutorial with examples of creating an array of random numbers. It also includes duplicate numbers and examples to get Random values from the javascript array.
Sometimes, We want to generate a fixed array with random values for testing and debugging.
javascript Random values generate an array
In this example, We will see how to create a random array with a size of 10
- using ES6 Math.random returns a number between 0 and 1, the more number you give, the possibility of duplicates is less. This creates a random array of size=10
let randomArray = Array.from(
{
length: 10,
},
() => Math.floor(Math.random() * 100),
);
console.log(randomArray);
Output:
[91,9,6,14,9,82,21,8,72,0]
- using for loop and push method Math.round returns the nearest rounded number
var randomArray = [];
for (let i = 0, j = 10; i < j; i++) {
randomArray.push(Math.round(Math.random() * 100));
}
console.log(randomArray);
Output
[87,12,28,75,68,94,45,36,72,92]
Random array with no repeated values in an array
Sometimes, We don’t want to allow duplicate values in a random array,
-
Create an empty array
-
Generate random numbers using
-
check if this number exists in the array, if not found, push it to an array
-
if found in an array, skip that number by not pushing to it
Here is an example of the random array without duplicates
var randomArray = [];
for (let i = 0, j = 10; i < j; i++) {
let randomNumber = Math.round(Math.random() * 100);
if (!randomArray.includes(randomNumber)) {
randomArray.push(randomNumber);
}
}
console.log(randomArray);
Output:
[96,20,61,91,80,60,95,33,4,69]
Conclusion
You learned to create random values in the array with or without repeated values in multiple ways.