-1

so I am trying to access the last item in the subclass of the array regardless of the size of the array.

All I got so far was undefined.

 var b = [['hello', 'goodbye'], ['hi', 'bye'], ['day', "night"]];

var first = b[0][0];
var last = b[0][b.length-1];

4 Answers4

2

You're getting the length of the first dimension, and using it in the second dimension. You need to get the length of the second dimension:

var last = b[0][b[0].length-1]
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Do you want "night"?

var last = b[b.length-1][b[b.length-1].length-1]
0

use the .length of the sub array, instead of the parent array. b.length refers to the parent/main array

 var b = [['hello', 'goodbye'], ['hi', 'bye'], ['day', "night"]];

var first = b[0][0];
var last = b[0][b[0].length-1];
console.log(last)
Junius L
  • 15,881
  • 6
  • 52
  • 96
0

you have an array b = [] which has elements, which themselves are arrays b =[[], [], []]

when you do b.length you get the length of the outermost array which in your case is 3, so it basically is doing this

b[0][3-1] => b[0][2] which is undefined

in languages like Java it would have been IndexOutOfBoundException

Therefore you need to change your approach to

b[0][b[0].length -1]

which will give you length of the inner array element, which is 2

b[0][2-1] => b[0][1] => 'goodbye'
Samip Suwal
  • 1,253
  • 11
  • 17