0

I have created a function where two different elements (randomColor1 and randomColor2) picks a color from the array. But the problem is sometimes both the elements(randomColor1 and randomColor2) pick the same color.

The value of both the element comes the same.

Here are my codes. Can you please tell me what is the exact code to rectify the issue. I want both elements selects different colors every from each other. I am new to javascript.

function GetValue() {
  var myarray = new Array("#ff0000", "#ffe100", "#95ff00", "#2c8d94","#911961");

  var randomColor1 = myarray[Math.floor(Math.random() * myarray.length)];
  var randomColor2 = myarray[Math.floor(Math.random() * myarray.length)];
  
  document.getElementById("message").innerHTML = randomColor1 + randomColor2;
}
Raj Jain
  • 15
  • 4

1 Answers1

4

Just remove the element that you are taking out of the array, to ensure you won't pick the same one again:

var randomColor1 = myarray.splice(Math.floor(Math.random() * myarray.length), 1)[0];
var randomColor2 = myarray.splice(Math.floor(Math.random() * myarray.length), 1)[0];
dave
  • 62,300
  • 5
  • 72
  • 93