Need of transposed[i] = []; when we already have var transposed = []

  • #1
shivajikobardan
524
33
TL;DR Summary
codewars kata confusion
What's the need of the commented code here?

JavaScript:
function transpose(matrix) {
  var transposed = [],
  rows = matrix.length,
  cols = matrix[0].length;
  for (i = 0; i < cols; i++) {
    // transposed[i] = [];
    for (var j = 0; j < rows; j++) {
      transposed[i][j] = matrix[j][i];
    }
  }
  console.log(transposed);
}
transpose([[1, 2, 3], [4, 5, 6]])

When that part is commented, it throws an error:
Uncaught TypeError: Cannot set properties of undefined (setting '0')

I'm trying to understand the need of it. Because we've already initialized
var transposed = [],
 
Last edited by a moderator:

Answers and Replies

  • #2
Filip Larsen
Gold Member
1,627
553
Do you understand how a matrix here is constructed as an array of arrays? You can also look in the loop body and ask yourself whattransposed[i][j]is supposed to mean iftransposed[i]is undefined (this is what gives the error you mention).

Edit: Writing[i]here without the code block is tricky because that is also notation for italics in posts. Took a few tries to figure out what was going on.
 

Suggested for: Need of transposed[i] = []; when we already have var transposed = []

Replies
1
Views
767
  • Last Post
Replies
2
Views
585
  • Last Post
Replies
10
Views
663
Replies
1
Views
586
Replies
15
Views
2K
  • Last Post
Replies
3
Views
352
  • Last Post
Replies
12
Views
183
Replies
12
Views
895
Top