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.
Creating arrays
Arrays consist of square brackets and elements that are separated by commas.
- Suppose we want to store a shopping list in an array. Paste the following code into the console:
- In the above example, each element 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:
let shopping = ['bread', 'milk', 'cheese', 'hummus',
'noodles']; shopping;
let sequence = [1, 1, 2, 3, 5, 8, 13];
let random = ['tree', 795, [0, 1, 2]];
Accessing and modifying array items
You can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string.
- Enter the following into your console:
- You can also modify an item in an array by giving a single array item a new value. Try this:
- 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:
shopping[0];
// returns "bread"
shopping[0] = 'tahini';
shopping;
// shopping will now return [ "tahini", "milk", "cheese",
"hummus", "noodles" ]
random[2][2];
Array length
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:
shopping.length;
// should return 5
This has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array. So for example:
let sequence = [1, 1, 2, 3, 5, 8, 13];
for (let i = 0; i < sequence.length; i++) {
console.log(sequence[i]);
}
Briefly, this code is saying:
- Start looping at item number 0 in the array.
- Stop looping at the item number equal to the length of the array. This works for an array of any length, but in this case it stops looping at item number 7 (this is good, as the last item — which we want the loop to include — is item 6).
- For each item, print it out to the browser console with console.log().
split()
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.
- Let's play with this, to see how it works. First, create a string in your console:
- Now let's split it at each comma:
let myData = 'Manchester, London, Liverpool, Birmingham, Leeds,
Carlisle';
let myArray = myData.split(',');
myArray;
join()
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
Using the example from the previous section, try the following:
let myNewString = myArray.join(',');
myNewString;
toString()
The toString() method returns a string representing the specified array and its elements. toString() is arguably simpler than join() to convert an array to a string as it doesn't take a parameter, but more limiting. With join() you can specify different separators, whereas toString() always uses a comma.
let dogNames = ['Rocket','Flash','Bella','Slugger'];
dogNames.toString(); // Rocket,Flash,Bella,Slugger
push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
- Include one or more items that you want to add to the end of your array. Try this:
- 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:
myArray.push('Cardiff');
myArray;
myArray.push('Bradford', 'Brighton');
myArray;
let newLength = myArray.push('Bristol');
myArray;
newLength;
pop()
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
- Try this:
- The item that was removed is returned when the method call completes. To save that item in a new variable, you could do this:
myArray.pop();
let removedItem = myArray.pop();
myArray;
removedItem;
Reference
All the documentation in this page is taken from MDN.