ninety nine
ninety nine

Reputation: 3

Javascript - Converting columns into rows

relatively new to JS, trying to understand this code which takes an array of arrays and converts its columns into arrays.

grid= 
[[".",".",".","1","4",".",".","2","."], 
[".",".","6",".",".",".",".",".","."], 
[".",".",".",".",".",".",".",".","."], 
[".",".","1",".",".",".",".",".","."], 
[".","6","7",".",".",".",".",".","9"], 
[".",".",".",".",".",".","8","1","."], 
[".","3",".",".",".",".",".",".","6"], 
[".",".",".",".",".","7",".",".","."], 
[".",".",".","5",".",".",".","7","."]]

//Turn columns into rows
var transpose = grid =>
    grid[0].map(
        (_,c) => grid.map(
            row => row[c]
        )
    )

How would this look using regular functions?

Upvotes: 0

Views: 528

Answers (1)

Martin Adámek
Martin Adámek

Reputation: 18359

var transpose = grid =>     // defining `transpose` as function with parameter `grid`, returning the following expression
    grid[0].map(            // return values from first row mapped via following function
        (_,c) => grid.map(  // using second parameter which is an index to do column mapping
            row => row[c]   // returning the value with index of row but from column
        )
    )

So without this ES6 map function, it would be 2 nested for cycles:

var grid = 
  [[".",".",".","1","4",".",".","2","."], 
  [".",".","6",".",".",".",".",".","."], 
  [".",".",".",".",".",".",".",".","."], 
  [".",".","1",".",".",".",".",".","."], 
  [".","6","7",".",".",".",".",".","9"], 
  [".",".",".",".",".",".","8","1","."], 
  [".","3",".",".",".",".",".",".","6"], 
  [".",".",".",".",".","7",".",".","."], 
  [".",".",".","5",".",".",".","7","."]];

function transpose(grid) {
    var ret = [];
    for (var i = 0; i < grid[0].length; i++) {
        ret[i] = [];
        for (var j = 0; j < grid.length; j++) {
            ret[i][j] = grid[j][i];
        }
    }

    return ret;
}

// use map for pretty printing the matrix
console.log(grid.map(row => row.join(' ')));
console.log(transpose(grid).map(row => row.join(' ')));

Upvotes: 1

Related Questions