Selecting 6 random elements from an array


#1

I am building a program which will change the colour of an element from the click of a button.

I want to create a function which will select 6 random elements from an array of 16 elements and return another array of the elements randomly selected.

The code below only returns 1 element, not 6 elements.

I’m unable to see where I’m going wrong. Please help…

function randCol() {
  for (var i = 0; i < 6; i++) {
  var colors = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e","f"];
    var rand = colors[Math.floor(Math.random() * 16)];
    var colArr = [];
    colArr.push(rand);
  }
  return "#" + colArr.join("")
}

function chngClr() {
 document.body.style.background = randCol();
}

#2

you should look close what you place inside your for loop, and what not

For example, defining the array (var colArr = [];) i wouldn’t put this in the loop, it means the values pushed to the array don’t persist, given each iteration of the loop the array declares itself again as empty array


#3

Yeah ur right. Let me try again.


#4

Done!!!

Such a silly mistake…

Thanks again man :+1:

function randCol() {
  var colArr = [];
  for (var i = 0; i < 6; i++) {
  var colors = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e","f"];
    var rand = colors[Math.floor(Math.random() * 16)];
    colArr.push(rand);
  }
  return "#" + colArr.join("")
}
                
function chngClr() {
 document.body.style.background = randCol();
}




#5

personally, i would also place this outside the loop as well:

var colors = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e","f"];

no need to create this array every iteration of the loop.


#6

Yeah ur right. No need to create arrays in every loop. Will remember…


#7

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