Home > database >  Javascript array nesting
Javascript array nesting

Time:11-05

This is a module from free code camp that I copied. I was wondering how the values 13 & 14 are called since it’s a nested array. Would you do [3] [1] [0] to call value 13?

Any help is greatly appreciated

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[[10, 11, 12], 13, 14]
];

const subarray = arr[3];
const nestedSubarray = arr[3][0];
const element = arr[3][0][1];

This wasn’t covered in the module just trying to understand how arrays work

CodePudding user response:

"... Was wondering how the values 13 & 14 are called since it’s a nested array. Would you do [3] [1] [0] to call value 13? ..."

No, you would use [3][1] for 13 and [3][2] for 14.
The third element of arr is [[10, 11, 12], 13, 14], and the first and second elements of this are, 13 and 14, respectively.

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[[10, 11, 12], 13, 14]
];

console.log(arr[3][1])
console.log(arr[3][2])

CodePudding user response:

Would you do [3] [1] [0] to call value 13?

No. Just arr[3][1] is enough to get the value 13. And arr[3][2] gets you 14.

You could explore this expression for yourself by logging each part.

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[[10, 11, 12], 13, 14]
];

console.log(arr); // the outermost array
console.log(arr[3]); // the inner array: [[10, 12,12], 13, 14]
console.log(arr[3][1]); // the number 13
console.log(arr[3][1][0]); // undefined (This is tricky! it's doing: 13[0])

Why 13[0] is undefined...

In JavaScript, when you try to do property access on a Number using [] you'll find that the number 13 is a thing called a Number instance which is an ordinary object but it doesn't have a property called "0", so it just results in undefined.

  • Related