简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM