1

in JS, when i create 2-d array, it seems that the coordinate is reversed. like array[y][x], instead of array[x][y]

var grades = [[89, 77, 78],
              [76, 82, 81],
              [91, 94, 89]];
print(grades[2][1]);  //94

how to reverse this coordinate?

var grades = [[89, 77, 78],
              [76, 82, 81],
              [91, 94, 89]];
function reverseCoordinate(grades){
   ......
}
print(grades[2][1]);  //81
vdj4y
  • 2,649
  • 2
  • 21
  • 31
  • 4
    Why don't you create the array the way you need it in the first place? Or use `grades[1][2]` instead. *"it seems the coordinates are reversed"* JS accesses exactly the element you tell it to access. – Felix Kling Jul 04 '14 at 16:43
  • Find the transpose of the array and assign this to the new array – Khushal Dave Jul 04 '14 at 16:46

1 Answers1

1

Matrices are accessed as matrix[row][col] in mathematics as well as programming. You should treat arrays of arrays as such in javascript.

To perform the transpose yourself, you could do a loop over the rows and then over the columns and assign it to a new array as column, row.

Strikeskids
  • 3,932
  • 13
  • 27