I want to get something like this: oranges
However no output is displayed. I tried printing via console and it doesn't work.
var array2 = ["Banana", ["Apples", ["Oranges"], "Blueberries"]];
I want to get something like this: oranges
However no output is displayed. I tried printing via console and it doesn't work.
var array2 = ["Banana", ["Apples", ["Oranges"], "Blueberries"]];
Since the desired fruit resides inside into third level, you have to use 3 indexes. Try array2[1][1][0]
.
Step by step:
array2[1] => ["Apples", ["Oranges"], "Blueberries"]
array2[1][1] => ["Oranges"]
array2[1][1][0] => Oranges
var array2 = ["Banana", ["Apples", ["Oranges"], "Blueberries"]];
console.log(array2[1][1][0]); // Oranges
you can use Destructuring assignment
on your array
but that's seem like overkill here
var array2 = ["Banana", ["Apples", ["Oranges"], "Blueberries"]];
let [,[,[orange]]] = array2
console.log(orange)
I added this answer to inform this way existed, BUT the answer from @Mamum is the way to go to when you need to get a small number of values from an array :
let orange = array2[1][1][0]
Welcome Joshua!
Arrays are accessible starting from index 0, so in order to access the inside array ["Apples", ["Oranges"], "Blueberries"]
you need to write array2[1]
since it is the second item in the array.
Next you need to access the ["Oranges"]
which is also the second item in that array, resulting in array2[1][1]
.
Finally since array2[1][1]
also returns an array containing "Oranges" in its first index (0), you have to write array2[1][1][0]
which will give you the result
console.log(array2[1][1][0])
Your arrays are currently nested, are you sure that's what you want? Since you have a pretty linear list of items here, I would suggest taking the internal arrays out:
var array2 = ["Banana", "Apples", "Oranges", "Blueberries"];
Array contents can be called by using the index number associated with the item you are trying to select. In this case:
console.log(array2[2]);
Here is the MDN documentation on JavaScript arrays, for your reference :)