Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Scott Peake
PLUS
Scott Peake
Courses Plus Student 6,796 Points

How does one determine length of a nested array?

We can use questions.length to determine how many elements are in the OUTER ARRAY, but what do we do to determine the length of an INNER ARRAY??

?!? questions[1].length ?!?

2 Answers

You are exactly right.

Consider this code:

var arr_of_arrs = [
                         [1, 2, 3],
                         [1, 2, 3, 4],
                         [1, 2, 3, 4, 5],
                         [1, 2, 3, 4, [5, 6]]
                                             ];
console.log(arr_of_arrs[0].length);

will log 3

console.log(arr_of_arrs[1].length);

will log 4

console.log(arr_of_arrs[2].length);

will log 5

console.log(arr_of_arrs[3].length);

will also log 5

and

console.log(arr_of_arrs.length);

will also log 4 (because there are 4 nested arrays)

and

console.log(arr_of_arrs[3][4].length);

will log 2

Can you see why?

(It's an array nested in an array nested in an array)

I hope that helps. Happy coding!

Scott Peake
Scott Peake
Courses Plus Student 6,796 Points

I was too lazy to test it out myself. While it seemed logical to me, I wasn't so sure. THANKS!

Scott,

You're welcome!

I don't know if it helps, but when I need to do a quick double-check (test) of some JS code I go here:

https://www.w3schools.com/js/tryit.asp?filename=tryjs_array

It saves a lot of environment set-up time when just trying to confirm how a small code snippet should execute, especially when a lot of the Treehouse challenges don't show you the RESULTS of your code, just if you passed or not (so it's hard sometimes to spot why!?!)

Have a great rest of the week!