Arrays

Arrays hold multiple values within one variable name.

Think of an array like a line-up of connected bins, each with its own home address (called an index). The individual values (or boxes) are called elements. Let's say you need to store ten random integers for a guessing game. You would not want to declare ten individual integer variables. Instead, you could declare one array variable of size 10 to hold the numbers.

You can store or retrieve each number by calling its address (index), typically using square brackets [ ]. Javascript shown here, other syntaxes shown in Example 1:

x[0] = 7;               // Store 7 in the first "bin"
let valueOfBin3 = x[2]; // Retrieve the value in the third "bin"

Note: A string is actually an array of char variables.

Declaring (Creating) an Array

Since Javascript does not have types like C++, we just make an array of variables. Javascript also has some great built-in methods that allow us to concatenate, join, search, and sort arrays (among other things). Note - in Javascript there is no need to declare empty arrays with an initial size.

// Let's declare an array, there are two ways to do it
let someArray = new Array();         // Bad way  :(
let otherArray = [];                 // Good way! :)

/* While both methods above work, it is considered 
   proper form to use the second method.            */

// Let's declare and put some values into arrays
let someIntegers = [40, 100, 1, 5, 25, 10];
let someLetters = ['a', 'c', "q", `k`];
let someBooleans = [true, false, false, false, true, false];
let someStrings = ["Hello", "Goodbye", "Some words", "Other words"];

// Javascript is such a loosely-typed language that
// your array can be mixed (not recommended)
let notRecommended = [6, -3, true, "Something in text", false, 'X'];

// You can create arrays on-the-fly as well
console.log( [6, 5, 4, 9, 8, 7] );

// Output will be:  [6, 5, 4, 9, 8, 7]

Lots more reading here and here.

Iterating Through Elements

Iterating is the process of going through each (or every nthn^{th}) element in an array.

You can retrieve the information of a single element by calling the index: x[5]; // Retrieve the element at index 5 (the 6th element)

In this same manner, you can loop through, or iterate through all the elements in an array.

This example prints the elements of an array. We could

// Let's put some values into an array
let someIntegers = [40, 100, 1, 5, 25, 10];

// Let's print out our array (Javascript has about 5 ways to do that)
for (let i = 0; i < someIntegers.length; i++) {
    console.log(someIntegers[i]);
}

// Using the for...of method
for (let value of someIntegers) {
    console.log(value);
}

Notice the use of someIntegers.length on line 5, above. In many languages you can retrieve the number of elements in this or similar ways. It is crucial to understand, however, that the value representing length is 1 higher than the last index in the array. For example, the following array has 8 elements but the last index is 7 because indexes start at zero.

let someValues = [45, 24, 3, 54, 245, 45, -6, 15];

// Length is 8
let arrayLength = someValues.length;

// There is no element at that location
console.log( someValues[arrayLength] );

// Output will most likely say "undefined" but could throw an exception as well

Modifying Arrays

Adding and removing elements from an array is memory-intensive. It is quite a process at the lowest-level, involving new memory space if growing your array and copying elements over. It can really slow down the program if doing this many thousands of times for large amounts of data.

Adding Elements

In Javascript, adding an element to the end of an array is very simple - you use the push() function. someArray.push(5) // Add integer 5 onto the end of the array someArray.push(7, 3, -9) // You can push multiple items in one command

The push() function returns a number representing the new length of the array.

If you want to insert a new element inside an existing array (or at the front), you need to utilize the splice() function. It is defined as myArray.splice(insertAt, 0, itemToInsert);

The splice function takes the parameters of where to insert the new item, how many items to delete (in this case, zero), and the item to insert. You can insert many items in one command.

Removing Elements

Removing the last element from the end of an array is done using the pop() function. someArray.pop() // Remove the last element

The pop() function returns the element it is removing.

Deleting elements within an array also uses the splice() function, similar to adding elements. The parameters you would use are the location and number of elements to remove: someArray.splice(5, 4) // Starting at index 5 remove 4 elements

Again, it will return a value representing the new length of the array.

Modifying the values in-place within an array for a strongly-typed language is much less memory intensive since each index simply points to a location in memory. Loosely-typed languages, like Javascript and Python, require much more memory-intensive work to modify an element, especially if changing the type (for example, swapping an integer for a large string of text).

Javascript:

let someIntegers = [ 5, 3, 1, 9, 7, 5 ];

// Let's print it:
console.log(someIntegers);

// Change the value at index 4
someIntegers[4] = 456;

// Print it again
console.log(someIntegers);

// OUTPUT:
//    [ 5, 3, 1, 9, 7, 5 ]
//    [ 5, 3, 1, 9, 456, 5 ]

Strings are Arrays

In programming, a string is actually an array of chars. Well, in reality a string is an object but I won't get into that here.

The string "Hello" is actually a char array of size 5 where char[0] = 'H', char[1] = 'e', char[2] = 'l', etc.

Most languages allow you to manipulate a string using the indexes of the characters. Also, when you append to a string or concatenate multiple strings together the computer must allocate a new chunk of memory that is the specific size of the new char array and individually assign each index the appropriate letter.

Multi-Dimensional Arrays

Simple arrays, as discussed in these sections, are called one dimensional arrays. They are linear in the sense that there is a beginning & end, and the indexes in-between have an element on either side, like links in a chain.

Arrays can be two dimensional as well (or even more). A 2D array has two indexes, [x, y], such that each element in the first index is, itself, an array.

You can also chain arrays into a 3D array. The idea there is that each element points to a 2D array of arrays. You can create all sorts of amazing combinations in this fashion.

Last updated