0

I have the following code which is supposed to get the clientHeight of certain elements and map them in a 2D array.

let columns = document.getElementsByClassName('_3Rcdf');
let cellHeights = new Array();

for (let row=0; row<columns[0].children.length; row++) {
    for (let j=0; j<columns.length; j++) {
        cellHeights[row, j] = columns[j].children[row].querySelector("._1KV2M").firstChild.firstChild.clientHeight;    
    }
}
console.log(cellHeights);

The log outputs the following: [151, 170, 151]

rather than the output of

[
[151,170,151],
[151,151,151],
[151,190,190],
[151,170,151]
]

What I am identifying is that the code is overwriting the values within the array with the latest 3 values, rather than creating a new array inside it. How can I fix this?

evilgenious448
  • 518
  • 2
  • 11
  • `cellHeights[row, j]` is the same thing as `cellHeights[j]`. Did you mean `cellHeights[row][j]`? – Sebastian Simon Nov 30 '22 at 09:15
  • 2
    Because JS doesn't implement multi-dimensional arrays, it can only emulate those with nested arrays. You've to create a new array to each "row" before assigning a value to it. – Teemu Nov 30 '22 at 09:16
  • @Teemu What is the best way to emulate those arrays so that the function would print the correct values into each one? I am not sure if using `push` would work since that would just add all 12 values into the array one after another without splitting into multiple arrays. – evilgenious448 Nov 30 '22 at 09:18
  • @SebastianSimon [that was the last problem](https://stackoverflow.com/q/74624547) – VLAZ Nov 30 '22 at 09:19
  • 1
    In the outer loop, create an array like `const col = []`, then in the inner loop populate `col` and finally push it to `cellHeights`. The variable names here are a bit confusing, though, as you've reserved `row` for another use, `col` above actually represents a "row" in the nested array. – Teemu Nov 30 '22 at 09:20
  • @Teemu Yeah it is a bit of a weird one with the rows and columns, since I only have access do the DOM tree and the way that the system is generating the elements, they are generated in columns rather than rows which is making this much more complicated than it needs to be haha – evilgenious448 Nov 30 '22 at 09:33

0 Answers0