javascriptfisher-yates-shuffle

How to shuffle an array of items


In the following example an array of numbers is shuffled each time the document is refreshed. How do I apply the same function that shuffles the numbers to shuffle the blocks of color?

const points = [1, 2, 3, 4, 5, 6];
document.getElementById("numbers").innerHTML = points;

function myFunction() {
  for (let i = points.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    let k = points[i];
    points[i] = points[j];
    points[j] = k;
  }
  document.getElementById("numbers").innerHTML = points;
}
<!DOCTYPE html>
<html>

<body onload="myFunction()">

  <div id="numbers"></div>

  <br>

  <div id="colors">
    <div style="width:50px; height:50px; background-color:red; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:yellow; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:blue; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:orange; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:green; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:purple; display:inline-block"></div>
  </div>

</body>

</html>


Solution

  • You can apply a shuffle directly to the DIVs. You start with an unshuffled region, and an initially empty shuffled region. You then pick items at random from the unshuffled region to place into the shuffled region.

    let p = document.getElementById('colors')
    let l = p.children.length
    for(let i=l+1; --i;) p.appendChild(p.children.item(Math.random()*i|0))
    <div id="colors">
        <div style="width:50px; height:50px; background-color:red; display:inline-block"></div>
        <div style="width:50px; height:50px; background-color:yellow; display:inline-block"></div>
        <div style="width:50px; height:50px; background-color:blue; display:inline-block"></div>
        <div style="width:50px; height:50px; background-color:orange; display:inline-block"></div>
        <div style="width:50px; height:50px; background-color:green; display:inline-block"></div>
        <div style="width:50px; height:50px; background-color:purple; display:inline-block"></div>
    </div>