Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Return 5 random numbers in range, first number cannot be zero - JavaScript
We are required to write a JavaScript function that generates an array of exactly five unique random numbers. The condition is that all the numbers have to be in the range [0, 9] and the first number cannot be 0.
Example
Following is the code −
const fiveRandoms = () => {
const arr = []
while (arr.length < 5) {
const random = Math.floor(Math.random() * 10);
if (arr.indexOf(random) > -1){
continue;
};
if(!arr.length && !random){
continue;
}
arr[arr.length] = random;
}
return arr;
};
console.log(fiveRandoms());
Output
This will produce the following output in console −
[ 9, 0, 8, 5, 4 ]
Advertisements
