Nested Arrays
An element of an array can be any value, even another array. An array inside an array is called a nested array. Nested arrays are useful for data that comes in groups, such as study groups:
const studyGroups = [["Jennifer", "Boris"], ["David", "Ava", "Nancy"]];
console.log(studyGroups);This prints:
[["Jennifer", "Boris"], ["David", "Ava", "Nancy"]]The array studyGroups has two elements, and each of them is an array of names: one study group. The first index selects a group, which is an ordinary array:
console.log(studyGroups[1]);This prints:
["David", "Ava", "Nancy"]To get one student, add a second index in square brackets. studyGroups[1][0] first takes the element at index 1 (the second group, ["David", "Ava", "Nancy"]) and then, from that array, the element at index 0:
console.log(studyGroups[1][0]);This prints:
DavidEverything you know about arrays works for the inner arrays too. studyGroups.length is 2, the number of groups, while studyGroups[1].length is 3, the number of students in the second group. And studyGroups[0].push("Tim") would add Tim to the end of the first group.
Instructions
- 1
Print the first member of the second team. Use two indexes.
- 2
Tim has joined the first team. Add
"Tim"to the end of the first team,teams[0], withpush(). - 3
Print the whole array
teams. The console should show[["Josh", "Emily", "Tim"], ["Daniel", "Ava"]].