** Explanation Needed ** Create complex multi-dimensional arrays

Here’s the example:

let nestedArray = [
  ['deep'],
  [
    ['deeper'], ['deeper'] 
  ],
  [
    [
      ['deepest'], ['deepest']
    ],
    [
      [
        ['deepest-est?']
      ]
    ]
  ]
];

And this code is being used to retrieve ‘deepest-est’.

console.log(nestedArray[2][1][0][0][0]);

Could anyone explain to me how the numbers came about? I have trouble identifying or counting the level of arrays.

Thanks in advance!

Have you tried

console.log("Level 0");
console.log(nestedArray[2]);
console.log("Level 1");
console.log(nestedArray[2][1]);
console.log("Level 2");
console.log(nestedArray[2][1][0]);
console.log("Level 3");
console.log(nestedArray[2][1][0][0]);
console.log("Level 4");
console.log(nestedArray[2][1][0][0][0]);
2 Likes

Whenever you are confused about nesting levels, slowly walk through the process.

Our nestedArray has three large elements.

Here is nestedArray[0]

Here is nestedArray[1]

Here is nestedArray[2]

The word we are looking for is in nestedArray[2]
This array has two elements

Here is the first one nestedArray[2][0]

Here is the second one nestedArray[2][1]

The word we are looking for is in nestedArray[2][1]
Inside this array we have just one array.

Now we have nestedArray[2][1][0]
Then we have another array inside that

Now we have nestedArray[2][1][0][0]

If you just want to return the string deepest-est? then we use bracket notation again to access the first element of that array.

Now we are at the final code of nestedArray[2][1][0][0][0]

Hope that helps!

2 Likes