Selecting a random object from an array

I have tried to select random thing from an array but it doesn’t work. Any advice?
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}
var colours = [
[“blue”, “green”, “red”],
]
var i = randomRange(1,3);
function randomColours() {
if(i == 1){
console.log(colours[0]);
} if(i == 2){
console.log(colours[1]);
} else {
console.log(colours[2]);
}
}
randomColours();
the output is
[ ‘blue’, ‘green’, ‘red’ ]

undefined

You are approaching the problem in a wrong way I think.
First try to use array.length as your max value.
Second you can get rid of all the if statement in the randomColor function if you work directly with array indexes starting from zero.
Third the randomRange function seems completely wrong to me.

Try to substitute the variables in that function with actual values (i.e. 1 and 3) and calculate the result manually, you should see where the error is.

1 Like

ah okey I have fixed it
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}
var colours =
[“blue”, “green”, “red”];

var i = randomRange(1,3);
function randomColours() {
if(i == 1){
console.log(colours[0]);
} if(i == 2){
console.log(colours[1]);
} if(i == 3) {
console.log(colours[2]);
}
}
randomColours();
and by the .length you mean like this?
const colours = [“blue”, “green”, “red”,];

const random = Math.floor(Math.random() * colours.length);

console.log(colours[random]);

Exactly. now it works?

you solved it anyway congs!

anyways code is for example,

const months = ["January", "February", "March", "April", "May", "June", "July"];

const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.