Nested Arrays

Arrays can contain other arrays to model complicated data structures. Take the following array that lists a persons name and age.

var people = [['bob', 34], ['jose', 18]]

The outer array and inner arrays can be indexed like any other array:

people[0]; // ['bob', 34]
people[0][1]; // 34

people[0] returns ['bob', 34], so people[0][1] is the same as ['bob', 34][1].

Here is how we can use the people array to create this names array: ['bob', 'jose'].

var names = [];
for (var i = 0; i < people.length; i++) {
  names.push(people[i][0]);
}
console.log(names); // ['bob', 'jose']

The following array of arrays contains groups of cities and their respective countries. The for loop iterates over the nested arrays and prints our information about each city to the console.

var cities = [['jarkata', 'indonesia'], ['bangalore', 'india']];
for (var i = 0; i < cities.length; i++) {
  var m = cities[i][0] + " is located in " + cities[i][1];
  console.log(m);
}

This loop prints the following output to the console:

jarkata is located in indonesia
bangalore is located in india

A nested array data structure can also be used to represent a student's name, telephone number, and course of study.

var students = [
  ['frank', '444-4444', 'biology'],
  ['saurabh', '333-3333', 'math'],
  ['tomo', '999-9999', 'finance']
}

Nested arrays are a powerful and flexible way to store data.

Question Click to View Answer

What does the following code print to the console?

var animals = [
  ["hawk", "bird"],
  ["shark", "fish"],
  ["gecko", "lizard"]
]
for (var i = 0; i < animals.length; i++) {
  var r = "A " + animals[i][0] + " is a " + animals[i][1];
  console.log(r);
}
A hawk is a bird
A shark is a fish
A gecko is a lizard

The code iterates through every element of the outer array and prints a formatted string to the console for each iteration.

What does the following code print to the console?

The following array shows two soccer players and their all-time career goals.

var players = [
  ["messi", 467],
  ["ronaldo", 502]
]
var totalGoals = 0;
for (var i = 0; i < players.length; i++) {
  totalGoals = totalGoals + players[i][1];
}
console.log(totalGoals);

969

messi and ronaldo have scored a combined 969 goals in their carrers.

<-- Previous (For Loops) Next (Nested Objects) -->