BTG Coding School

Arrays

Welcome back. So far we’ve looked at ways to combine our code in various ways to achieve more powerful programs. Now we’ll start looking at how we can combine data, which will make it easier to represent certain types of problems for a computer.

The simplest way of combining data is with an Array. An array is a list of values. All the values are stored next to each other, so the computer can efficiently find a particular value if you provide its position.

Lets look at how arrays are created in Javascript:

let my_array = [2, 4, 6, 8, 10];
for (let i = 0; i < my_array.length; i++) {
  console.log("The value at position " + i + " is " + my_array[i]);
}

Feel free to copy that into the devtools console and watch it work.

Inside the computer, that array would look something like this:

There are a few key things to point out. If we want to represent an array value in Javascript, we use square brackets ([ and ]). Then, we represent each value separated by a comma.

The number of values stored in an array can be accessed with .length. The elements of the array start and 0, and continue to include length - 1. The reasons for starting at 0 have to do with how arrays work internally. Just remember that we’ll start with 0.

We look up a given element of an array by providing the name of the array variable, square brackets, then its position, often called its index.

You may notice that this looks very similar to strings, which we saw in the types lesson. Strings behave very similar to arrays. One noticable difference is that we can modify arrays in Javascript, but not Strings (we had to create a new one).

Modifying an array is just like accessing it. Here’s a loop that will double each of the values:

let arr = [2, 4, 6, 8, 10];
for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i] * 2;
    // note, we also could have written
    // arr[i] *= 2;
}
console.log(arr);

Nesting arrays

Javascript lets you put any value you want into an array. They can even be of different types, though that is often not recommended. Usually you want to be able to write code that handles each element of the array in a similar way.

// We can put strings in an array.
let arr = ["Liam", "Olivia", "Noah"];

// We can also put arrays in arrays. The spacing here is not required, but just
// to make it easier to read.
// Each element represents [Name, Age]
let arr = [
    ["Liam", 15],
    ["Olivia", 18],
    ["Noah", 20],
];
for (let i = 0; i < arr.length; i++) {
    // This gets the item in the outer array. This item will be an array.
    let entry = arr[i];
    // These are the inner items of the array. First is a string, then a number.
    let name = entry[0];
    let age = entry[1];
    console.log(name + " is currently " + age + " years old.");
}

Perhaps you can already see how arrays will allow us to represent many more types of scenarios inside our programs.

Adding to arrays

You can also add a new value to the end of an array with push().

let arr = [];
for (let i = 0; i < 10; i++) {
    arr.push(i * 2);
}
console.log(arr);

Typically, pushing aka appending to the end of an array is slow. Arrays are not growable, so appending an element actually requires creating a new array with enough space, then copying everything over.

Javascript actually does something tricky here, which we’ll cover more in the next lesson. Generally, however, arrays let you look up a value instantly, and adding an element takes time based on how many values there were (since it needs to copy them all).

Exercises

  1. Write a function find_max, which takes an array of numbers and gives back the largest number.

    Hint You'll want to keep track of the largest value seen so far. If the list has no elements, you can just return -1.

  2. Write a function that takes a list of numbers, and gives us back a new array with only the even numbers.

Solutions

  1. function find_max(arr) {
        if (arr.length == 0) {
            return -1;
        }
        let max = arr[0];
        for (let i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        return max;
    }
    
  2. function only_evens(arr) {
        let result = [];
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] %2 == 0) {
                result.push(arr[i]);
            }
        }
        return result;
    }
    

Next Lesson: Dictionaries / Hash tables

Arrays allow us to solve many problems efficiently. But sometimes we want to look up a value using something other than a number. We’ll learn how to do that in the next lesson about hash tables.