How to rotate non square two dimensional array twice to have all possible rotations?
You could use the length of the array for calculating the new positions.
original left right -------- -------- -------- 1 2 3 4 1 3 6 4 5 6 5 2 2 5 6 3 1 4
function rotateRight(array) {
var result = [];
array.forEach(function (a, i, aa) {
a.forEach(function (b, j, bb) {
result[bb.length - j - 1] = result[bb.length - j - 1] || [];
result[bb.length - j - 1][i] = b;
});
});
return result;
}
function rotateLeft(array) {
var result = [];
array.forEach(function (a, i, aa) {
a.forEach(function (b, j, bb) {
result[j] = result[j] || [];
result[j][aa.length - i - 1] = b;
});
});
return result;
}
var array = [[1, 2, 3], [4, 5, 6]];
console.log(rotateLeft(array));
console.log(rotateRight(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }