1

I would like to "mirror" (like seen in a mirror) a 2-d array. The array looks like that:

array1 = [
  ['a','b','c'],
  ['d','e','f'],
  ['g','h','i'],
  ['j','k','l']
];

I'd like to create a new array which values "mirror" the first array values, like that:

array2 = [
  ['a','e','i'],
  ['b','f','j'],
  ['c','g','k'],
  ['d','h','l']
];

Been trying a couple of thing with reverse() but I cannot find a solution.

Edit: in this case "mirror" means something similar to Cramer's Rule: http://www.1728.org/cramer4d.png (see diagonals)

Edit: My bad, I should have copy-proofed my post. The second array should like:

array2 = [
  ['a','d','g','j'],
  ['b','e','h', 'k'],
  ['c','f','i', 'l']
];
Remka
  • 69
  • 1
  • 8

1 Answers1

2

The basic idea is flatten the array of arrays, with Array.prototype.reduce like this

var array1 = [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['g', 'h', 'i'],
    ['j', 'k', 'l']
];

var flatArray = array1.reduce(function(result, currentArray) {
    return result.concat(currentArray);
}, []);

console.log(flatArray);
# [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' ]

And then, for every element, get the element after the length of the individual arrays, like this

var rows = array1.length,
    cols = array1[0].length + 1,
    result = [];

for (var i = 0; i < rows; i += 1) {
    var temp = [];
    for (var j = 0; j < cols - 1; j += 1) {
        temp.push(flatArray[i + (j * cols)]);
    }
    result.push(temp);
}

console.log(result);

Output

[ [ 'a', 'e', 'i' ],
  [ 'b', 'f', 'j' ],
  [ 'c', 'g', 'k' ],
  [ 'd', 'h', 'l' ] ]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497