
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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