Arrays: Lists of Data

Arrays: Lists of Data
1and1 placeholder image

In this lesson, we'll take a look at a very common data type which consists of a collection of other data types called arrays. Usings arrays, you can store numbers, strings, objects, even other arrays, inside a single variable.

Creation

When you want to handle a collection of the same data type, you'll want to create an array. Here's an example of how to create one.

	
    var drinks = ["water", "juice", "milk", "soda"];
	

Just like that, you've created a new array with four elements in them, and initiated the value of drinks with it.

Retrieval

Now that you've put data inside the array, how do you retrieve it? If you specify the index, you can get the value at that index back.

Because Javascript is zero-based (it starts counting from 0 instead of 1), water is actually at position 0 in the array, not 1.

So, if you wanted to get back the first element in the array, it would be like this:

	
    console.log(drinks[0]);
	
	
    water
	

You can take this a step further and iterate over the entire array using a for loop.

	
    var drinks = ["water", "juice", "milk", "soda"];

    for (var i = 0; i < drinks.length; i++) {
        console.log(drinks[i]);
    }
	
	
    water
    juice
    milk
    soda
	

We are initializing the value of i to be 0, and then looping until that value is equal to the number of elements in the array, in this case, 4.

As the value goes from 0 to 1, to 2, and then to 3, the values at each of those indexes is being logged to our console.

1and1 placeholder image

Reassignment

After you have initialized an array, you can modify the values at an index pretty easily. Say you want to replace milk with coffee, it is as simple as this:

	
    var drinks = ["water", "juice", "milk", "soda"];

    drinks[2] = "coffee";

    console.log(drinks);
	
	
    ["water", "juice", "coffee", "soda"]
	

All you need to do is provide the index you want to reassign and then set it equal to your new value.

Methods

JavaScript has a bunch of built-in methods we can use with our arrays to make common tasks simple and painless. Let's go over the most popular ones.

Sort

You can sort you array by calling the sort method on it.

	
    var drinks = ["water", "juice", "milk", "soda"];

    var sortedDrinks = drinks.sort();

    console.log(sortedDrinks);
	
	
    ["juice", "milk", "soda", "water"]
	

In the case of strings, it will sort the items alphabetically. Here's how to sort an array of numbers numerically:

	
    var numbers = [31, 99, 2, 6, 27, 64];

    numbers.sort(function(a, b) {
        return a - b;
    });
	
	
    (6) [2, 6, 27, 31, 64, 99]
	

We can pass to sort a compare function that takes two items, compares them, and then returns true or false to determine which element should be in front of the other. In our case, since we are working with numbers, we simply get the difference between the two values. A positive difference returns true and a negative difference returns false. This sorts the array of numbers as we want to.

Push

With push, you can easily add new items to the end of your array. Just call push on your array with the new item you want to add.

	
    var drinks = ["water", "juice", "milk", "soda"];

    drinks.push("tea"); // add "tea" to the end of this array

    console.log(drinks);
	
	
    ["water", "juice", "milk", "soda", "tea"]
	

Pop

Pop is the opposite of push. Call pop on your array to remove the last item in your array.

	
    var drinks = ["water", "juice", "milk", "soda"];

    drinks.pop(); // remove the last item in this array

    console.log(drinks);
	
	
    ["water", "juice", "milk"]
	

Shift

The shift method removes the first element of an array and then returns that element to you.

	
    var chocolates = ["Snickers", "Kit-Kat", "Twix"];

    var snack = chocolates.shift();

    console.log(snack);
    console.log(chocolates);
	
	
    Snickers
    ["Kit-Kat", "Twix"]
	

Unshift

The unshift method adds elements to the beginning of the array and returns the new array's length to you.

	
    var chocolates = ["Snickers", "Kit-Kat", "Twix"];

    var newLength = chocolates.unshift("Milky Way", "3 Musketeers");

    console.log(newLength);
    console.log(chocolates);
	
	
    5
    ["Milky Way", "3 Musketeers", "Snickers", "Kit-Kat", "Twix"]
	

Concat

You can create a new array by concatenating two existing arrays. All you need to do is call concat on one array, with the second array being the parameter.

	
    var healthyDrinks = ["water", "milk"];
    var unhealthyDrinks = ["juice", "soda"];

    var allDrinks = healthyDrinks.concat(unhealthyDrinks);
    console.log(allDrinks);
	
	
    ["water", "milk", "juice", "soda"]
	

Slice

Using slice, you can return a brand new array containing elements from a slice of the original array. Simply provide the method with the starting and ending indexes and it will do the rest.

	
    var colors = ["purple", "red", "white", "blue", "gold"];

    var slice = colors.slice(1, 4);
    console.log(slice);
	
	
    ["red", "white", "blue"]
	

If you only provide one parameter, it will use that number as the starting point, and copy the rest of the array.

	
    var colors = ["purple", "red", "white", "blue", "gold"];

    var slice = colors.slice(3);
    console.log(slice);
	
	
    ["blue", "gold"]
	

Finally, if you provide a negative index, it will just start from the end and go backwards to reach the starting index.

	
    var colors = ["purple", "red", "white", "blue", "gold"];

    var slice = colors.slice(-3);
    console.log(slice);
	
	
    ["white", "blue", "gold"]
	

Splice

The splice method accomplishes a similar task as slice except that splice returns the elements removed instead of the elements requested. splice also changes the original array, whereas slice creates an entirely new one.

	
    var foods = ["burger", "pizza", "donut", "bread", "pasta"];

    foods.splice(2);
    console.log(foods);
	
	
    ["burger", "pizza"]
	

If you provide a second parameter, you can specify the number of elements to remove from the array starting from that index.

	
    var foods = ["burger", "pizza", "donut", "bread", "pasta"];

    foods.splice(2, 1);
    console.log(foods);
	
	
    ["burger", "pizza", "bread", "pasta"]
	

In this case we are going to index 2, which is donut, then removing 1 element. Thus, the new food array is every item except for donut.

Split

The split method is used when you want to take a string and chop it into an array every time a certain character is encountered in that string. For example, here is splitting on the comma character:

	
    var string = "peanut,butter,jelly,time";
    var array = string.split(",");

    console.log(array);
	
	
    (4) ["peanut", "butter", "jelly", "time"]
	

The text has been split up by the character we passed in.

Join

The join method is the opposite of the split method. It takes an array of strings and concatenates them while inserting a character in between all the array elements to return a new string.

	
    var array = ["peanut", "butter", "jelly", "time"];
    var string = array.join(",");

    console.log(string);
	
	
    peanut,butter,jelly,time
	

indexOf

The indexOf method returns to you the index in the array where the item you pass as a parameter is found. Simply put, pass along what you want to find and indexOf will tell you where it's at. Let's see an example:

	
    var array = ["Tilted Towers", "Pleasant Park", "Greasy Grove", "Fatal Fields"];
    var index = array.indexOf("Greasy Grove");

    console.log(index);
	
	
    2
	

In our example, we had an array of 4 elements, and we wanted to know what index Greasy Grove was in. Upon calling indexOf, the result was 2. That makes sense when you remember that the first element in an array has an index of 0 and not 1. That is why the third element in the array has an index of 2.

lastIndexOf

As you might imagine, lastIndexOf is very similar to indexOf except instead of returning the first/lowest index the element appears in, it returns the last. Let's try using the method to search for an element found multiple times.

	
    var array = ["Tilted Towers", "Pleasant Park", "Greasy Grove", "Fatal Fields", "Pleasant Park", "Loot Lake"];
    var index = array.lastIndexOf("Pleasant Park");

    console.log(index);
	
	
    4
	

The element we used lastIndexOf with appears twice in our array, but since the method returns the last index, it returned 4 instead of 1.

includes

The includes method return a boolean indicating if the element you pass in as a parameter exists in the array. It will return true if the element exists, or false if it does not.

	
    var array = ["Tilted Towers", "Pleasant Park", "Greasy Grove", "Fatal Fields", "Pleasant Park", "Loot Lake"];
    var a = array.includes("Tilted Towers");
    var b = array.includes("Retail Row");

    console.log(a);
    console.log(b);
	
	
    true
    false
	

find

The find method is a pretty useful method that returns the first element that passes a test that you define. You define a test as a function that takes an element as a parameter and returns true if the element passed the test or false if the element failed the test. The first element to pass the test gets returned.

	
    var ages = [43, 24, 37, 28, 49, 68, 63, 21, 63, 79];

    function canRetire(number) {
        return number >= 65;
    }

    console.log(ages.find(canRetire));
	
	
    68
	

Since 68 was the first element in the array to pass the test, which was to be equal to or greater than 65, that number was returned.

findIndex

The findIndex method simply returns the index of the element you would have gotten if you used find.

	
    var ages = [43, 24, 37, 28, 49, 68, 63, 21, 63, 79];

    function canRetire(number) {
        return number >= 65;
    }

    console.log(ages.findIndex(canRetire));
	
	
    5
	

The sixth element with the index of 5 was returned since it was the first element to pass the test.

Reverse

You can reverse all the elements of an array by calling JavaScript's reverse method on an array.

	
    var cities = ["New York", "Boston", "Los Angeles", "Houston", "Miami", "Chicago"];
    cities.reverse();

    console.log(cities);
	
	
    (6) ["Chicago", "Miami", "Houston", "Los Angeles", "Boston", "New York"]
	

Every

The method every can be used to ensure that every element in the array meets a certain criteria. You can define this criteria by passing in a function the returns a boolean representing whether or not that criteria was met. Here's an example:

	
    var ages = [23, 52, 42, 32, 19];

    function isAnAdult(age) {
        return age >= 18;
    }

    console.log(ages.every(isAnAdult));
	
	
    true
	

Since every number is equal to or greater than 18, the every method returned true. Watch when a single value does not meet the criteria though:

	
    var ages = [23, 52, 15, 32, 19];

    function isAnAdult(age) {
        return age >= 18;
    }

    console.log(ages.every(isAnAdult));
	
	
    false
	

As you might expect, because a single number in the entire array did not meet the criteria of being greater than or equal to 18, the every method returned false.

Some

The some method is sort of like the inverse of the every method. While every requires that all elements meet the criteria, the some method only requires a single element to meet the criteria. In other words, only some, even a single element, need to meet the criteria for the entire method to return true.

	
    var numbers = [64, 23, 86, 38, 47, 119];

    function isTripleDigit(number) {
        return number >= 100;
    }

    console.log(numbers.some(isTripleDigit));
	
	
    true
	

Since we had a single element that was a triple-digit number, 119, the method returned true, but watch when we do not have a single element that meets the criteria:

	
    var numbers = [64, 23, 86, 38, 47, 32];

    function isTripleDigit(number) {
        return number >= 100;
    }

    console.log(numbers.some(isTripleDigit));
	
	
    false
	

No elements in our array was a triple-digit number so the some method returned false.

forEach

The forEach method calls a function you provide on every element in your array, in the order they appear in the array. It automatically passes in the element and index for you. This is another way you can iterate across an entire array and do something with each element.

	
    var greetings = ["hello", "hola", "ciao", "bonjour"];

    function logGreeting(element, index) {
        console.log(index, element);
    }

    greetings.forEach(logGreeting);
	
	
    0 "hello"
    1 "hola"
    2 "ciao"
    3 "bonjour"
	

Map

The map function creates a new array from an existing one after calling a function on every element. Consider this scenario:

	
    var names = ["Bill", "Kelly", "John"];

    var intros = names.map(function(name) {
    	return "My name is " + name;
    });

    console.log(intros);
	
	
    ["My name is Bill", "My name is Kelly", "My name is John"]
	

It took every element from the names array, prepended every string element with My name is and the result was a new array with three brand-new strings.

This function does not alter the original array.

Filter

The filter method is useful for, well, filtering out elements you don't want from an array to form a new one.

	
    var numbers = [1, 2, 3, 4, 5, 6, 7, 8];

    var odd = numbers.filter(function(number) {
        return number % 2 == 1;
    });

    console.log(odd);
	
	
    [1, 3, 5, 7]
	

Essentially, your filter function simply needs to return true or false. Only elements that cause the function to return true end up moving on to the new array, and the rest are filtered out.

Reduce

The reduce method goes over every element and collects some information about each element, and then finally returns the collective result.

A simple way to demonstrate reduce is to use it to sum up all the numbers in an array.

	
    var numbers = [1, 2, 3, 4, 5, 6, 7, 8];

    var total = numbers.reduce(function(total, number) {
        return total + number;
    });

    console.log(total);
	
	
    36
	

Instead of adding the numbers together, you can do anything you'd like and reduce will return the final result for you.

Arrays are pretty cool as they make it easier to work with multiple pieces of data at the same time, but in our next lesson, we'll discuss objects!