Skip to content Skip to sidebar Skip to footer

Javascript: Shuffle 2d Array

What is the best way to shuffle a 2D array in javascript ? I need my 2D array to be shuffled after being created. will this be a good solution of doing this? thx

Solution 1:

I have done that once for a Tile Map in a 2D Game.

for (let i = 0; i < mapSizeY; i++) {
    for (let j = 0; j < mapSizeX; j++) {
        var rand = Math.floor(Math.random() * 4) + 0;
        map[i][j] = rand;
    }
}

This generated a random Number between 0 and 3 for each tile

Solution 2:

You can use lodash. It's javascript lib for array manipulation.

You can shuffle with lodash:

_.shuffle(yourArray);

https://lodash.com/docs#shuffle

Post a Comment for "Javascript: Shuffle 2d Array"