Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  199] [ 4]  / answers: 1 / hits: 27950  / 6 Years ago, mon, march 5, 2018, 12:00:00

I have this array:



rows = [ [ 89, 18, 9 ], [ 1903, 3, 4 ], [ 3, 1, 800 ] ];


It should look like this:



[ [ 89, 1903, 3 ], [ 18, 3, 1 ], [ 9, 4, 800 ] ]


And the code, that is working, looks like this:



rows[0].map((_, columnIndex) => rows.map(
row => row[columnIndex])
);


How does this work?


More From » javascript

 Answers
103
                  +--- The outter function map gets the first array to loop through the rows
[ 89, 18, 9 ] |
[ 1903, 3, 4 ] |
[ 3, 1, 800 ] v
+--->
|
+- The nested function map is looping through the columns.
The key here is the fixed column using index (column[index])
from the outter function map, so every iteration from the outter
function map will fix the access to that column, i.e -
index = 0 will access the array as follow: array[j][0], array[j+1, 0], ... array[n, 0]
^ ^ ^


This is an approach to illustrate what's happening using direct index accesses.



var rows = [ [ 89, 18, 9 ], [ 1903, 3, 4 ], [ 3, 1, 800 ] ];

var result = [];
for (var i = 0; i < rows[0].length; i++) {
result[i] = new Array(rows[0].length).fill();

for (var j = 0; j < rows.length; j++) {
result[i][j] = rows[j][i]; // Here is the fixed column access using the outter index i.
}
}

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




[#55007] Thursday, March 1, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emerald

Total Points: 547
Total Questions: 96
Total Answers: 122

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;