We are required to write a JavaScript function that takes in a number, say n, and an array of two numbers that represents a range. The function should return an array of n random elements all lying between the range provided by the second argument.
Example
Following is the code −
const num = 10; const range = [5, 15]; const randomBetween = (a, b) => { return ((Math.random() * (b - a)) + a).toFixed(2); }; const randomBetweenRange = (num, range) => { const res = []; for(let i = 0; i < num; ){ const random = randomBetween(range[0], range[1]); if(!res.includes(random)){ res.push(random); i++; }; }; return res; }; console.log(randomBetweenRange(num, range));
Output
This will produce the following output in console −
[ '13.25', '10.31', '11.83', '5.25', '6.28', '9.99', '6.09', '7.58', '12.64', '8.92' ]
This is just one of the many possible outputs.
Let us run again to get a different random output −
[ '5.29', '7.95', '11.61', '7.83', '10.56', '7.48', '12.96', '6.92', '8.98', '9.43' ]