I'm currently facing a problem where I have to shift data in a multidimensional JS array in different directions, but I think the first solution I whipped up is not as efficient as it could be (some fancy math I don't know of maybe?).
Let me explain the problem a bit better with some examples of my data.
This is the array in question:
[1][0][1][0][1][0]
[0][1][1][0][0][0]
[0][0][1][0][1][1]
[0][0][0][0][1][1]
[0][0][1][1][0][0]
[1][0][0][1][1][1]
If I shifted it to the left, it should look like this:
[1][1][1][0][0][0]
[1][1][0][0][0][0]
[1][1][1][0][0][0]
[1][1][0][0][0][0]
[1][1][0][0][0][0]
[1][1][1][1][0][0]
Or down
[0][0][0][0][0][0]
[0][0][0][0][0][0]
[0][0][1][0][1][0]
[0][0][1][0][1][1]
[1][0][1][1][1][1]
[1][1][1][1][1][1]
To put it simple - shift 1's as far as possible.
The code I wrote is fairly simple
for (w = 0; w < arraySize; w++) {
for (h = 0; h < arraySize; h++) {
tiles = $('.arrayContainer .row').eq(w).children();
if (tiles.eq(h).html() != "" && tiles.eq(h - 1).html() == "" && (h-1) >= 0) {
tiles.eq(h - 1).html(tiles.eq(h).html());
tiles.eq(h).html("");
}
}
}
This will shift values left-to-right by one step. arraySize
is the variable that determines the size of the array, tiles
gets each row of the array output.
If I wasn't here, posting and wouldn't think this could be done better I'd create four of these structures and just live with it, but I'm pretty sure this can be done better.