Skip to main content

Javascript: Arrays

Basic Array Structure

An array is a type of basic data structure that lets us store and access information like numbers, strings, or even other arrays. Unlike objects, the order of items in an array matters. Without arrays we could define a set of strings as variables like this:

var cat1 = "lion"

var cat2 = "tiger"

var cat3 = "leopard"

var cat4 = "tabby"

but a better way to store and access these variables would be in an array.

var cats = ["lion", "tiger", "leopard", "tabby"]

REMEMBER: Arrays are indexed starting at 0. So the above array would be indexed as so:

liontigerleopardtabby
0123

Referencing Items in the Array

The basic structure to reference items in the array is this. If I wanted to reference leopard from the above array i would do this:

cats[2] //leopard

You simply add the [ ] brackets to the end of the table name and then input the index of the item you would like to call. Roll tide.

Modify Items in the Array

You can modify an item in the array just like you would a variable, you simply reference it and then set it equal to something else. For example if I decide that a tabby is not quite fierce enough for this array, I can simply reference it and then set it equal to something else:

cats[3] = "jaguar";

cats[3] //jaguar

Add Items to Array

We can add items to the array in the exact same way. To add a 5th cat to the table we can simply reference the 4th index (which does not currently exist) and pass it a string!

cats[4] = "hobbes";

and now our table looks like this:

liontigerleopardjaguarhobbes
01234

Array Properties

.length

To find out how many items are in an array use the .length property:

cats.length //5

*note: this will return the total number of items, not the final index number which would be 1 less.

.push

adds an item automatically to the end of the array without having to figure out what the last index is and count it manually.

cats.push("panther");

would go ahead and add panther to the end of the array at index 5.

.pop

this will automatically delete the last item in the array.

cats.pop(); //removes the panther that we just added at index 5

.unshift()

Very similar to .push, except .unshift will add an item to the front of the array.

.shift()

and .shift will remove an item from the front.

Storing Items in a Variable

One very common thing to do when you are removing items from an array is to store them in another variable. For example:

var firstCat = cats.shift();

//lion

lion is stored in variable firstCat

So as you can see here we made an array of cats and the first cat is the lion. Then we created a variable called firstCat and set that equal to the first item of the array which we have essentially pulled out of the cats array and set to its own variable.

.indexOf()

This is a VERY important property. It allows us to search an array for specific string and then returns the position of that string in the array. If there are duplicated in the array it will return the first instance of that string. So if we take the following array:

var cats = ["lion", "tiger", "leopard", "tabby"];

and we want to locate the position of “leopard” we would input:

cats.indexOf(leopard)

which we can then set into its own variable:

var leopardIndex = cats.indexOf("leopard");

leopard index is 2

NOTE If an item is not present in an array, .indexOf() will return -1

Using this we can do a quick check if an item is in an array.

.slice()

Slice copies a section of an array which you define with a quick range. For example if we have our cats array

liontigerleopardjaguarhobbes
01234

and we want to copy the middle 3 cats to a new array, lets call it favoriteCats we would do the following:

var favoriteCats = cats.slice(1,4);

So index 1 starts the slice at tiger, and then index 4 ends the slice at hobbes. Note that the ending index is not included in the slice that is taken, it stops just before then.

new array called favorite cats with 3 cats, and old array called cats with 5

Note that slice did not remove those three cats from the array, it just copied them and added them to a new one.

.splice()

Very similar to .slice except .splice will actually REMOVE an item from the array. The first argument is the index of the item to be removed and the second is the number of items to be removed.

splicing one cat out of array

Nested Arrays

You can actually nest arrays inside of arrays. So for example if we take

var nestedArraySample = [

["blue", 56, "yellow"],

[45, "twenty", "argentina"],

["tidal", "spotify", 404],

]

what if we wanted to select spotify? Spotify is in the 3rd array, which is index 2, and it is in index 1 of that array, so we would select it with:

nestedArraySample[2][1];

spotify selected

Array Iteration

A practical example of an array iteration would be a list of comments to be displayed on a post. The comments are stored in an array and you want to loop over all of them to display them on a page!

This is accomplished by combining loops with arrays! Here we will discuss for loops and forEach loops.

To start, one of the most basic pieces of information that we have to understand about an array if we want to display every item is the length of the display. Which is accomplished with the .length property.

For looping all items in an array

If we want to console.log() all of the items in an array we could do the following:

var cats = ["lion", "tiger", "leopard", "tabby"];

for(var i = 0; i < cats.length; i++){
console.log(cats[i]);
}

all cats logged in list

.forEach()

A new (as of 2009) and better way to list items in an array is the .foreach() method. Which is designed to do just this task. The big difference here is that this method takes a function as its argument. So the basic format is this:

anArray.forEach(some function)

and the someFunction takes an argument which essentially acts as a placeholder just for the sake of this function, that it uses as it loops through the array. For example:

var cats = ["lion", "tiger", "leopard", "tabby"];

We have an array called cats

cats.forEach(function(cat){
//the code
console.log(cat);
});

**** THE KEY HERE is that the cat variable is a placeholder value that could be ANYTHING. We are just putting it here so that we can call it in //the code wherever we want!

** Syntax Notes: This must be .forEach, if you do not capitalize the E it will not run

Another thing to understand about the .foreach method is that it can take three argument, the first one we have gone over here, but the second and third we have not. The second is the index of the current item, and the third is the name of the index. MDN notes on this are available HERE.

Comments

Recent Work

Free desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.

Learn More

BidBear

bidbear.io

Bidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.

Learn More