0

I need to detect the length of an inner array within a 2d array in my application. But unfortunately it always raises a "TypeError: Cannot read property 'length' of undefined" error. Does anyone detect an error? Thanks a bunch

This is the 2d array called currentNodeData (I get this with the following command --> console.log(currentNodeData)):

enter image description here

And this is how I want to receive the length of the inner array, which should be 6:

console.log(currentNodeData[0].length);

And this is the error:

enter image description here

Rainer Winkler
  • 485
  • 1
  • 7
  • 20
  • Most likely caused by [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/q/4057440) – VLAZ Jan 12 '21 at 15:25
  • @VLAZ - Maybe, although we see the `Array(6)` in the summary line, which normally we wouldn't. Still, that's what fits the symptom. Rainer, are you sure your screenshot isn't from a different run then the error is? – T.J. Crowder Jan 12 '21 at 15:26
  • Side note: JavaScript doesn't have multi-dimensional arrays. It has arrays of arrays, which are not the same thing. But assuming `currentNodeData` is an array containing another array at index 0, then `currentNodeData[0].length` is the correct way to get the length of the array at index 0. – T.J. Crowder Jan 12 '21 at 15:28
  • Hmmmm.. ok thanks for clarifying, but how can you explain that currentNodeData[0].length does not work in my case? – Rainer Winkler Jan 12 '21 at 15:41

1 Answers1

0

what is currentNodeData in your case?

lets review:

So we have an Array inside the array.

Lets name it :

const innerArray = [{id:1}, {id: 2}, {id: 3}, {id: 4}]
const outer = [innerArray];

the outer array will have only one inner array? if yes: we can do the next thing:

outer[0].length // 4

or we can use flat()

outer.flat().length // 4

const innerArray = [{id:1}, {id: 2}, {id: 3}, {id: 4}]
const outer = [innerArray];

console.log(outer[0].length);
console.log(outer.flat().length);

Also we should understand that your variable can be assigned asynchronously, and in this case your varibale could be empty at the time when you try to get the length.

Let's try to reproduce:

In this example, we can see an error, because data is not assigned yet

let outer = []; 
setTimeout(() => {outer = [[{id:1}]]}, 1000)
console.log(outer[0].length)

in this case we should add Optional chaining operator or ?. And at the first time we will see undefined, and when data is assigned we should check it again, and we will see length

let outer = []; 
setTimeout(() => {outer = [[{id:1}]]}, 1000)
console.log(outer[0]?.length)
setTimeout(() => {console.log(outer[0]?.length)}, 1000)
shutsman
  • 2,357
  • 1
  • 12
  • 23