Rotating a rectangular array in Javascript

I am trying to make a tetris game. I am trying to work on a function that rotates a 2D variable array 90 degrees (or -90).

For example, given an array like:


I would like an output like:


etc, etc.

I have tried this function:

function rotateN90(a){
    var temp = [];
    for(var x = 0; x<a[0].length; x++){
        for(var y = 0; y<a.length; y++){
            temp[x] += a[y][x];
    return temp;

but it does not give the desired result. While it does rotate the first T-Block example given -90 degrees once, afterwards it reverts to it’s original state.

Please help!

(PS: I am using KA’s processing environment, so I can’t use libraries)

16 thoughts on “Rotating a rectangular array in Javascript”

Leave a Comment