{ Nested Arrays. }

Objectives:

By the end of this chapter, you should be able to:

  • Create and access values in two dimensional arrays
  • Understand real-world use cases of multidimensial arrays
  • Iterate over data in a multidimensional array

Multidimensional Arrays

Multidimensional arrays are a special kind of nested data structure, which consists of an array, each of whose elements is again an array. Here's an example:

var myFirstSubarray = [["this", "is"], ["super", "cool"]];

When working with two-dimensional arrays, if you want to print out all of the values, you are going to need a loop inside of a loop! Let's examine this a bit further.

var nestedArr = [[1, 2], [3, 4]];
for (var i = 0; i < nestedArr.length; i++) {
  console.log(nestedArr[i]);
}

// this will log out...
// [1,2]
// [3,4]

But what if we want to print out each individual value (i.e. 1, 2, 3, 4), and not just each array? We will need another loop inside of the first loop! We traditionally initialize the inner counter as j (the letter that comes after i) and we will loop as long as j is less than the length of each inner array.

var nestedArr = [[1, 2], [3, 4]];
for (var i = 0; i < nestedArr.length; i++) {
  for (var j = 0; j < nestedArr[i].length; j++) {
    // notice that we are going inside the outer array
    // and now inside of the inner array
    console.log(nestedArr[i][j]);
  }
}

// this will log out...
// 1
// 2
// 3
// 4

Here is an another example - take a quick look and try to replicate it without looking at the code!

var nestedArr = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10, 11, 12]];
for (var i = 0; i < nestedArr.length; i++) {
  for (var j = 0; j < nestedArr[i].length; j++) {
    console.log(nestedArr[i][j]);
  }
}

So when are two-dimensional arrays used? Quite often! For example, when building games you can often model the game board like a nested array. You can use a nested array for a tic-tac-toe board, a Minesweeper board or maybe for a couple hands of poker!

Additional Resources

An excellent post on accessing nested resources - http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json

Exercises

Given the following array, write a function called printEvens that console.logs all of the even numbers

var nestedArr = [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12]];

printEvens();

// 2
// 4
// 6
// 8
// 10
// 12

Given the following array, write a function called sumTotal returns the sum of all numbers in the array

var nestedArr = [[1, 2], [3, 4], [5, 6]];

sumTotal(); // 21

Here's what a solution might look like for the sumTotal function:

function sumTotal() {
  var total = 0;
  for (var i = 0; i < nestedArr.length; i++) {
    for (var j = 0; j < nestedArr[i].length; j++) {
      total += nestedArr[i][j];
    }
  }
  return total;
}

Optional Bonus

Given the following array, write a function called countVowels, which returns the count of all of the vowels in each string regardless of case. To see if a value is an array, you can not use typeof since that will return 'object', so one way to do this is by using the Array.isArray function.

var arr = [];
Array.isArray(arr); // true
Array.isArray("Hello"); // false

var nestedArr = [
  "Elie",
  ["Matt", ["Tim"]],
  ["Colt", ["Whisky", ["Janey"], "Tom"]],
  "Lorien"
];

countVowels(); // 13

Optional Bonus Solution

Here is a solution using iteration, as you continue to learn more about programming, you'll see that this is an excellent use case for recursion (writing a function that calls itself).

function seeIfVowel(char, count) {
  var vowels = "aeiou";
  if (vowels.includes(char.toLowerCase())) {
    return ++count; // add 1 to count then return the value (this is called a prefix operator)
  }
  return count;
}

function countCharacters(str, count) {
  for (var i = 0; i < str.length; i++) {
    count = seeIfVowel(str[i], count);
  }
  return count;
}

function countVowels(arr) {
  var count = 0;
  for (var i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      for (var j = 0; j < arr[i].length; j++) {
        if (Array.isArray(arr[i][j])) {
          for (var k = 0; k < arr[i][j].length; k++) {
            if (Array.isArray(arr[i][j][k])) {
              for (var l = 0; l < arr[i][j][k].length; l++) {
                count = countCharacters(arr[i][j][k][l], count);
              }
            } else {
              count = countCharacters(arr[i][j][k], count);
            }
          }
        } else {
          count = countCharacters(arr[i][j], count);
        }
      }
    } else {
      count = countCharacters(arr[i], count);
    }
  }
  return count;
}

function countVowelsEasier(arr) {
  var str = arr.toString();
  var count = 0;
  count = countCharacters(str, count);
  return count;
}

When you're ready, move on to Nested Arrays Exercises

Continue

Creative Commons License