# Selecting 6 random elements from an array

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.

``````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();
}
``````

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

2 Likes

Yeah ur right. Let me try again.

Done!!!

Such a silly mistake…

Thanks again man

``````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();
}

``````
1 Like

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.

2 Likes

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

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