Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firefox and Google Chrome differences creating or sorting an array using .sort(() => Math.random() – 0.5);

I’m trying to make a minesweeper, and something weird has happened, in Chrome or Chromium-based navigators everything seems and works just fine, but in firefox, all of the bombs generated clumped together at the end, or the start of the array, is there any difference in how sort() works with parameters?

I’ll leave the piece of the code that generates the board.

  

    function createBoard() {
        //create an array with shuffled bombs
        const bombsArray = Array(bombAmount).fill("bomb");
        const emptyArray = Array(width * width - bombAmount).fill("valid");
        const gameArray = emptyArray.concat(bombsArray);
        const shuffledArray = gameArray.sort(() => Math.random() - 0.5);
        for (let i = 0; i < width * width; i++) {
          const square = document.createElement("div");
          square.setAttribute("id", i);
          square.classList.add(shuffledArray[i])
          grid.appendChild(square);
          squares.push(square);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the documentation:

Note: compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments.

In your case, you don’t do this, which gives undefined behaviour, most likely dependent on the sorting algorithm that is used by the browser’s Array.sort implementation.

You can ensure that the random value for a particular array item remains stable by mapping to a new array with a random order property, sorting, then mapping back again:

const shuffledArray = gameArray
  .map((value) => ({ value, order: Math.random() }))
  .sort((a, b) => a.order - b.order)
  .map(({ value }) => value)

This probably isn’t the most efficient way of shuffling an array, but a minesweeper board is so small that it won’t matter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading