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:

David

Everything 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

Print the first member of the second team. Use two indexes.

Tim has joined the first team. Add "Tim" to the end of the first team, teams[0], with push().

Print the whole array teams. The console should show [["Josh", "Emily", "Tim"], ["Daniel", "Ava"]].

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

9/11

Next