1

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"]];
4

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't questions like this be closed against their canonical dups? What value does this questions and the answers add to the site for future visitors?
2

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]

7 Comments

Though your answer is correct, however, in my opinion it is too much of an ask from a person who is learning how to access nested array
@NikhilAggarwal yeah I know I just wanted to inform that it existed, also upvoted array2[1][1][0] since this is the correct one
Thanks for the assist @bamieh
I like this one, but maybe it could be a mess for learners. Why don't you include the short array2[1][1][0] in your answer? Just in case this answer rise to the top.
@Emeeus like this ?
|
1

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])

Comments

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.