Files
freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.md
Lasse Jørgensen 9fcd4f5c16 fix(curriculum): change data type and verbiage (#52595)
Co-authored-by: Naomi Carrigan <nhcarrigan@gmail.com>
2023-12-19 15:50:36 +00:00

122 lines
1.9 KiB
Markdown

---
id: 56533eb9ac21ba0edf2244cd
title: Accessing Nested Arrays
challengeType: 1
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
forumTopicId: 16160
dashedName: accessing-nested-arrays
---
# --description--
As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, array bracket notation can be chained to access nested arrays.
Here is an example of how to access a nested array:
```js
const ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1];
ourPets[1].names[0];
```
`ourPets[0].names[1]` would be the string `Fluffy`, and `ourPets[1].names[0]` would be the string `Spot`.
# --instructions--
Using dot and bracket notation, set the variable `secondTree` to the second element in the `list` array from the second object in the `myPlants` array.
# --hints--
`secondTree` should equal the string `pine`.
```js
assert(secondTree === 'pine');
```
Your code should use dot and bracket notation to access `myPlants`.
```js
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(x) {
if(typeof x != 'undefined') {
return "secondTree = " + x;
}
return "secondTree is undefined";
})(secondTree);
```
## --seed-contents--
```js
const myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
const secondTree = "";
```
# --solutions--
```js
const myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
const secondTree = myPlants[1].list[1];
```