1

I have an array of strings and require just 4 of these (randomly) to be placed into another array.

var a = ["Orange", "Red", "Yellow", "Blue", "Black", "White", "Brown", "Green"];
var b = [];
function selectColours(){
    var toRandomise = a[Math.floor(Math.random() * 4)];
    b.push(toRandomise);
}
console.log(b);

My problem is that the Console shows nothing appearing.

2
  • 2
    Are you calling selectColours()? Commented May 13, 2016 at 12:30
  • This way you can't get any further than "Blue". Replace a[Math.floor(Math.random() * 4)]with a[Math.floor(Math.random() * a.length)] Commented May 13, 2016 at 14:07

2 Answers 2

3

Well, you're not really running the function you created. Simply declaring it.

Just write selectColors(); right before the console.log

Sign up to request clarification or add additional context in comments.

3 Comments

Doing this only shows one random string, not the 4 that I require to e stored in the array.
If you want four strings, rather than one you should put it in a loop. Right now you're just getting a random number between 0 and 3. Also note, that if you don't want results to be duplicated (Having two "Red"s for instance) you need to remove the elements.
I see where I am going wrong now and a loop has solved it, thankyou.
2

You also need add random value 4 times so you can use for loop

var a = ["Orange", "Red", "Yellow", "Blue", "Black", "White", "Brown", "Green"];
var b = [];

function selectColours() {
  for (var i = 0; i < 4; i++) {
    var toRandomise = a[Math.floor(Math.random() * 4)];
    b.push(toRandomise);
  }
}

selectColours()
console.log(b);

You can also use recursion.

var a = ["Orange", "Red", "Yellow", "Blue", "Black", "White", "Brown", "Green"];
var b = [], count = 0;


function selectColours() {
  if (count == 4) return true;
  b.push(a[Math.floor(Math.random() * 4)]);
  count++;
  selectColours();
}

selectColours()
console.log(b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.