What Is an Array?

Site: Saylor Academy
Course: PRDV402: Introduction to JavaScript II
Book: What Is an Array?
Printed by: Guest user
Date: Wednesday, September 18, 2024, 9:22 PM

Description

An array is a way to store a collection of multiple items under a single variable name. This section introduces how to create, delete and access array elements.  Think about the following as you read the article:

  • How are array elements accessed?
  • What methods are used to access the elements of an array?
  • How would you convert a string into an array?


Arrays

We'll look at arrays - a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.

Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective: To understand what arrays are and how to manipulate them in JavaScript.

Source: Mozilla, https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays#what_is_an_array
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.

What is an array?

Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we've got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom.

If we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. This would be much longer to write out, less efficient, and more error-prone. If we had 10 items to add to the invoice it would already be annoying, but what about 100 items, or 1000? We'll return to this example later on in the article.

Creating arrays

Arrays consist of square brackets and items that are separated by commas.

  1. Suppose we want to store a shopping list in an array. Paste the following code into the console:
  2. const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
    console.log(shopping);
  3. In the above example, each item is a string, but in an array we can store various data types - strings, numbers, objects, and even other arrays. We can also mix data types in a single array - we do not have to limit ourselves to storing only numbers in one array, and in another only strings. For example:

    const sequence = [1, 1, 2, 3, 5, 8, 13];
    const random = ["tree", 795, [0, 1, 2]];
  4. Before proceeding, create a few example arrays.

Finding the length of an array

You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string - by using the length property. Try the following:

const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping.length); // 5

Accessing and modifying array items

Items in an array are numbered, starting from zero. This number is called the item's index. So the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item's index, in the same way that you accessed the letters in a string.
  1. Enter the following into your console:
  2. const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
    console.log(shopping[0]);
    // returns "bread"
  3. You can also modify an item in an array by giving a single array item a new value. Try this:
  4. const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
    shopping[0] = "tahini";
    console.log(shopping);
    // shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]

    Note: We've said it before, but just as a reminder - computers start counting from 0!

  5. Note that an array inside an array is called a multidimensional array. You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this:

  6. const random = ["tree", 795, [0, 1, 2]];
    random[2][2];
  7. Try making some more modifications to your array examples before moving on. Play around a bit, and see what works and what doesn't.

Finding the index of items in an array

If you don't know the index of an item, you can use the indexOf() method. The indexOf() method takes an item as an argument and will either return the item's index or -1 if the item is not in the array:

const birds = ["Parrot", "Falcon", "Owl"];
console.log(birds.indexOf("Owl")); //  2
console.log(birds.indexOf("Rabbit")); // -1

Adding items

To add one or more items to the end of an array we can use push(). Note that you need to include one or more items that you want to add to the end of your array.

const cities = ["Manchester", "Liverpool"];
cities.push("Cardiff");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff" ]
cities.push("Bradford", "Brighton");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff", "Bradford", "Brighton" ]

The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:

const cities = ["Manchester", "Liverpool"];
const newLength = cities.push("Bristol");
console.log(cities); // [ "Manchester", "Liverpool", "Bristol" ]
console.log(newLength); // 3

To add an item to the start of the array, use unshift():

const cities = ["Manchester", "Liverpool"];
cities.unshift("Edinburgh");
console.log(cities); // [ "Edinburgh", "Manchester", "Liverpool" ]

Removing items

To remove the last item from the array, use pop().

const cities = ["Manchester", "Liverpool"];
cities.pop();
console.log(cities); // [ "Manchester" ]

The pop() method returns the item that was removed. To save that item in a new variable, you could do this:

const cities = ["Manchester", "Liverpool"];
const removedCity = cities.pop();
console.log(removedCity); // "Liverpool"

To remove the first item from an array, use shift():

const cities = ["Manchester", "Liverpool"];
cities.shift();
console.log(cities); // [ "Liverpool" ]

If you know the index of an item, you can remove it from the array using splice():

const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
  cities.splice(index, 1);
}
console.log(cities); // [ "Manchester", "Edinburgh", "Carlisle" ]

In this call to splice(), the first argument says where to start removing items, and the second argument says how many items should be removed. So you can remove more than one item:

const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
  cities.splice(index, 2);
}
console.log(cities); // [ "Manchester", "Carlisle" ]

Accessing every item

Very often you will want to access every item in the array. You can do this using the for...of statement:

const birds = ["Parrot", "Falcon", "Owl"];

for (const bird of birds) {
  console.log(bird);
}


Converting between strings and arrays

Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the split() method. In its simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array.

Note: Okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here.

  1. Let's play with this, to see how it works. First, create a string in your console:
  2. const data = "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle";
  3. Now let's split it at each comma:
  4. const cities = data.split(",");
    cities;
  5. Finally, try finding the length of your new array, and retrieving some items from it:
  6. cities.length;
    cities[0]; // the first item in the array
    cities[1]; // the second item in the array
    cities[cities.length - 1]; // the last item in the array
  7. You can also go the opposite way using the join() method. Try the following:
  8. const commaSeparated = cities.join(",");
    commaSeparated;
  9. Another way of converting an array to a string is to use the toString() method. toString() is arguably simpler than join() as it doesn't take a parameter, but more limiting. With join() you can specify different separators, whereas toString() always uses a comma. (Try running Step 4 with a different character than a comma).
  10. const dogNames = ["Rocket", "Flash", "Bella", "Slugger"];
    dogNames.toString(); // Rocket,Flash,Bella,Slugger

Conclusion

After reading this article, we are sure you will agree that arrays seem pretty useful; you will see them crop up everywhere in JavaScript, often in association with loops to do the same thing to every item in an array. Now you should give yourself a clap and take a well-deserved break; you've worked through all the sections in this article!