{ 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:

let 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.

let nestedArr = [[1, 2], [3, 4]];
for (let 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.

let nestedArr = [[1, 2], [3, 4]];
for (let i = 0; i < nestedArr.length; i++) {
  for (let 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!

let nestedArr = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10, 11, 12]];
for (let i = 0; i < nestedArr.length; i++) {
  for (let 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

let 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

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

sumTotal(); // 21

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

function sumTotal() {
  let total = 0;
  for (let i = 0; i < nestedArr.length; i++) {
    for (let 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.

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

let nestedArr = [
  "Elie",
  ["Matt", ["Tim"]],
  ["Colt", ["Whiskey", ["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) {
  let 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 (let i = 0; i < str.length; i++) {
    count = seeIfVowel(str[i], count);
  }
  return count;
}

function countVowels(arr) {
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      for (let j = 0; j < arr[i].length; j++) {
        if (Array.isArray(arr[i][j])) {
          for (let k = 0; k < arr[i][j].length; k++) {
            if (Array.isArray(arr[i][j][k])) {
              for (let 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) {
  let str = arr.toString();
  let count = 0;
  count = countCharacters(str, count);
  return count;
}

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

Continue

Creative Commons License