0

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?

3
  • What do you mean by “regular” functions? Commented Oct 29, 2017 at 23:13
  • 1
    add an explanation on what you should want as result. Commented Oct 29, 2017 at 23:13
  • Do you mean using "for" loops? Commented Oct 29, 2017 at 23:15

1 Answer 1

1
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(' ')));

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, extremely precise and clear response.. Appreciate the expertise and help very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.