How to use arrays and discover their full potential

Arrays are amazing in Javascript. They are so useful for keeping track of data, finding information, and for local functions as well. In this guide, I’ll tell (and show) you why arrays are so amazing and give you some examples of how to use them.

This guide is assuming you know nothing about arrays, but are familiarized with Javascript.

So the first thing you have to know is that arrays can be defined with square brackets. ([]) Two square brackets with nothing in them is an empty array – arrays are essentially lists of items of any type.

const array = [];

If you want to define your array with items at the beginning, you can insert them in between the square brackets. Separate items with commas if you have multiple:

const array = [1, 2, 3, "hello", true];

Unlike other languages like C#, one array can have any other data type in it – even other arrays! (we’ll get to that later though)

If you want to find a specific item in an array, you can use its index. Each item in an array has its own index, starting with 0 for the first item, 1 with the second item, 2 with the third, and so on. You can use bracket notation to get the item of a specific index:

const array = [1, 2, 3, "hello", true];
console.log(array[0]);
// Outputs: 1

But what if you don’t know the index of the item? Then you can use the indexOf method to find the index of a specific item.

const array = [1, 2, 3, "hello", true];
console.log(array.indexOf("hello"));
// Outputs: 3

Note that it returns the first index of the item in the array.

In this example the player is asked which item they want to find, and it responds with where the item is in the array:

const array = ["apple", "orange", "lemon", "pear", "grape"];
const item = window.prompt("Which item do you want?");
console.log("That item is at index " + array.indexOf(item) + " of the array!");

If the item doesn’t exist in the array, it returns -1. Let’s make it so it doesn’t give the user -1 if they choose an invalid item. A ternary operator can be used to make the code quicker and more concise. If you want to learn more about ternary operators, I suggest you go here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

const array = ["apple", "orange", "lemon", "pear", "grape"];
const item = window.prompt("Which item do you want?");
const message = array.indexOf(item) >= 0 ? "That item is at index " + array.indexOf(item) : "Invalid item!";
console.log(message);

This code checks if the index of the item is equal to or greater than 0 (which it will be if the item exists), and then sets message to either the index or a string depending on if it is.

So, arrays are already pretty useful. But there are still much, much more uses of them. Introducing, the for…of loop!

const array = [1, 2, 3, "hello", true];

for (let item of array) {
     console.log(item);
}

The for…of loop, well, loops through each item of an array! If you’d like a function instead, you can use the forEach method:

array.forEach(item => {
     console.log(item);
});
// Acts the same

Note: For…of loops are NOT for…in loops! For…of loops are reserved for iterating arrays and other array-like variables, while for…in loops are for iterating objects.

Push and Unshift

Push and unshift are very useful methods for adding items to arrays. We’ll get to removing items later.
Note: push and unshift mutate the array, so they directly edit the array instead of returning a new one

The push method adds an item to the end of the array.

const array = ["apple", "orange"];
array.push("lemon");
console.log(array);
// Outputs: ["apple", "orange", "lemon"]

While the unshift method adds an item to the front of an array.

const array = ["apple", "orange"];
array.unshift("lemon");
console.log(array); 
// Outputs: ["lemon", "apple", "orange"]

If you’d like to replace an item, just edit the item of the index you’d like to replace.

const array = ["apple", "orange", "lemon"];
array[array.indexOf("orange")] = "melon";
console.log(array);
// Outputs: ["apple", "melon", "lemon"]

Slice and Splice

Slice and Splice are very useful methods for removing items.
Note: slice returns an array, while splice mutates the array.

The slice method slices the array to only the 2 indexes specified (the end index not included).

const array = ["apple", "orange", "lemon", "pear", "grape"];
array = array.slice(0, 2);
console.log(array);
// Outputs: ["apple", "orange"]
const array = ["apple", "orange", "lemon", "pear", "grape"];
array = array.slice(1, 4);
console.log(array);
// Outputs: ["orange", "lemon", "pear"]

The splice method, on the other hand, does the opposite: it slices the specified indexes, but instead of returning that portion, it deletes that portion, leaving only the rest.

const array = ["apple", "orange", "lemon", "pear", "grape"];
array = array.splice(0, 2);
console.log(array);
// Outputs: ["lemon", "pear", "grape"]
const array = ["apple", "orange", "lemon", "pear", "grape"];
array = array.splice(1, 4);
console.log(array);
// Outputs: ["apple", "grape"]

To make it simple, slice and splice both cut out a part of the array, but slice returns that part, while splice removes that part.

Other useful methods

The pop method removes the last item in array – the opposite of push.

const array = ["apple", "orange", "lemon", "pear", "grape"];
array.pop();
console.log(array);
// Outputs: ["apple", "orange", "lemon", "pear"]

The filter method returns a new array with all the items that met the condition specified.

const array = [1, 2, 3, 4, 5];
const results = array.filter(item => item >= 3);
console.log(results);
// Outputs: [3, 4, 5]
const array = ["apple", "orange", "lemon", "orange", "grape"];
const results = array.filter(item => item == "orange");
console.log(results);
// Outputs: ["orange", "orange"]

The find method returns the first item that matches the condition set. It’s like filter, but only the first item.

const array = [1, 2, 3, 4, 5];
const result = array.find(item => item >= 3);
console.log(result);
// Outputs: 3

The includes method checks if the array includes a specific item:

const array = ["apple", "orange", "lemon", "pear", "grape"];
console.log(array.includes("lemon")); // Outputs: true
console.log(array.includes("peach")); // Outputs: false

Earlier we said how the indexOf method only returned the first index of the item inputted. Well, the lastIndexOf method returns the last index of the item.

const array = ["apple", "pear", "lemon", "pear", "grape"];
console.log(array.indexOf("pear")); // Outputs: 1
console.log(array.lastIndexOf("pear")); // Outputs: 3

The map method is a powerful one that iterates through each item of an array and changes them:

const array = [1, 2, 3, 4, 5];
const mapped = array.map(item => item * 2);
console.log(mapped);
// Outputs: [2, 4, 6, 8, 10]
const array = ["apple", "orange", "lemon", "pear", "grape"];
const mapped = array.map(item => item + "s");
console.log(mapped);
// Outputs: ["apples", "oranges", "lemons", "pears", "grapes"]

The sort method sorts an array either inside the default way or in a special method that you input.
The default sorting for numbers is 0-9 for the first digit.

const array = [1, 60, 23, 9, 100];
array.sort();
console.log(array);
// Outputs: [1, 100, 23, 60, 9]

The default sorting for strings is A-Z for the first digit as well.

const array = ["apple", "orange", "lemon", "pear", "grape"];
array.sort();
console.log(array);
// Outputs: ["apple", "grape", "lemon", "orange", "pear"]

Examples of using your own sorting methods:

const array = [1, 60, 23, 9, 100];
array.sort((a, b) => a - b);
console.log(array);
// Outputs: [1, 9, 23, 60, 100];
const months = ["March", "Jan", "Feb", "Dec"];
const monthOrder = ["Jan", "Feb", "March", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
months.sort((a, b) => monthOrder.indexOf(a) - monthOrder.indexOf(b));
console.log(months);
// Outputs: ["Jan", "Feb", "March", "Dec"]

Arrays and Strings

There are a variety of ways to convert between arrays and strings. The most common ones are join and split. Let’s look at join first.

The join method returns a string with each item of an array in it, separated by a string that you input.

const array = ["apple", "orange", "lemon", "pear", "grape"];
const string = array.join(", ");
console.log(string);
// Outputs: "apple, orange, lemon, pear, grape"

If you don’t input any joining string, it will automatically join them with a comma.

The split method does the opposite: it splits a string into an array, separated by a string that you input.

const string = "apple, orange, lemon, pear, grape";
const array = string.split(", ");
console.log(array);
// Outputs: ["apple", "orange", "lemon", "pear", "grape"]

If you don’t input any joining string in the split method, it’ll return an array with one item: the entire string.

And of course, you can convert the array straight into a string with the common toString method:

const array = ["apple", "orange", "lemon", "pear", "grape"];
const string = array.toString();
console.log(string);
// Outputs: "apple,orange,lemon,pear,grape"

The Next Dimension

Arrays are already super useful, but we’ve only been working with 1 dimensional arrays – one line of items that can stretch to infinity. You can, however, add another dimension and make a table – a 2d array. I like to call each item of a 2d array a row, and each item of each row a column, though you don’t have to.

const oneDimensionalArray = [1, 2, 3, "hello", true];

const twoDimensionalArray = [
     ["row 0 column 0", "row 0 column 1"],
     ["row 1 column 0", "row 1 column 1"],
     ["row 2 column 0", "row 2 column 1"]
];

You can get a specific item from a 2d array using double bracket notation:

console.log(twoDimensionalArray[1][0]);
// Outputs: "row 1 column 0"

You can even make a 3d array, 4d array, 5d array, and so on! Each array will become progressively more advanced and harder to manage, but it’s worth it for large projects.

console.log(fourDimensionalArray[3][4][1][0]);
// Outputs: "row 3 column 4 layer 1 sheet 0"

That’s All, Folks!

I hope you now understand why arrays are incredible to work with in javascript (for me at least), and I hope you learned how to use them more efficiently in your projects!
Thanks for reading, and see you in the next article!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.