Arrays: Lists of Data

Arrays: Lists of Data

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.


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.

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


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:


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

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

    for (let i = 0; i < drinks.length; i++) {

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.


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:

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

    drinks[2] = "coffee";

    ["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.


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

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

    const sortedDrinks = drinks.sort();

    ["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:

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


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.

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

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

    ["water", "juice", "milk", "soda", "tea"]


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

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

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

    ["water", "juice", "milk"]


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

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

    const snack = chocolates.shift();

    ["Kit-Kat", "Twix"]


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

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

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

    ["Milky Way", "3 Musketeers", "Snickers", "Kit-Kat", "Twix"]


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.

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

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


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.

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

    const slice = colors.slice(1, 4);
    ["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.

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

    const slice = colors.slice(3);
    ["blue", "gold"]

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

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

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


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.

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

    ["burger", "pizza"]

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

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

    foods.splice(2, 1);
    ["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.


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:

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

    (4)ย ["peanut", "butter", "jelly", "time"]

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


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.

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



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:

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


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.


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.

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


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.


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.

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



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.

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

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


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.


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

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

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


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


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

    const cities = ["New York", "Boston", "Los Angeles", "Houston", "Miami", "Chicago"];

    (6)ย ["Chicago", "Miami", "Houston", "Los Angeles", "Boston", "New York"]


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:

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

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


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:

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

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


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.


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.

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

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


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:

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

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


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


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.

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

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

    0 "hello"
    1 "hola"
    2 "ciao"
    3 "bonjour"


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

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

    const intros = {
    	return "My name is " + name;

    ["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.


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

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

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

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


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.

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

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


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!