DEV Community

Miguelito
Miguelito

Posted on

function in JS

Guys, help me write a function in JS:

a function that will return a new array based on the existing 'features' array; the length of the new array X (a random number, but not more than the length of the existing array 'features');

function randomNumber(min, max, afterPoint) {
if (min >= 0 && max >= 0 && afterPoint >= 0) {
const rand = min + (Math.random() * (max - min));
return Number(rand.toFixed(afterPoint));
}
return 'The range can only be positive, including zero!';
}
randomNumber(0, 10, 0);

// existing array
const features = ['wifi', 'dishwasher', 'parking', 'washer', 'elevator', 'conditioner'];

Top comments (2)

Collapse
 
mellen profile image
Matt Ellen

To start with you want to generate a random number based on the length. I see you have a function that will do that, but it seems overly complicated for our needs. I would just use Math.random and Math.ceil, i.e. let newLength = Math.ceil(Math.random()*features.length);

Then you want the new array, for which I would use Array.prototype.slice like so: let portion = features.slice(0, newLength);

Collapse
 
mihel17 profile image
Miguelito

Thank you very much! You`re a true professional