• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

220
Views
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);

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error