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 ]