arrays

February 7, 2023 - Reading time: 9 minutes

I learned a few things about JavaScript on OpenClassrooms (taking Apprenez à programmer avec JavaScript Écrivez du JavaScript pour le web courses). I didn't know it then but I was actually looking for DOM manipulation for my Qwixx project. Anyway, I'm refreshing my newbie knowledge by taking FreeCodeCamp JavaScript Algorithms and Data Structures course and here is a recap about arrays.

Store

An array can store multiple pieces of data in a single variable. Each entry is separated by a comma and nested into square brackets. Just like this:

const SANDWICH = ["peanut butter", 1, true, ["bakery", "home-made"]];

An array containing another array is also called a multi-dimensional array. An array can also contain objects.

Access

"peanut butter" 1 true ["bakery", "home-made"]
0 1 2 3

Arrays use zero-based indexing, so the first element in an array has an index of 0. Use square bracket notation to get the data associated to the index. For instance:

console.log(SANDWICH[0]);
const EATEN = SANDWICH[1];
console.log(EATEN);

will print "peanut butter" string and 1 number.

Note that additional pair of brackets refers to the next level of entries inside.

const BOUGHT_IN = SANDWICH[3][0];
console.log(BOUGHT_IN);

will print "bakery".

Check for the presence of an element

Use indexOf() method. It returns -1 if the item is not found. For instance:

SANDWICH.indexOf('peanut butter'); // returns 0 
SANDWICH.indexOf('butter'); // returns -1

Call for all items of an array

Use spread operator (...). For instance (from FreeCodeCamp):

const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // maximus has the value of 89

Iterate through

Use a for loop. It looks like this:

let array = [1, 2, 3]
for (let i = 0; i < array.length; i++) {
console.log(array[i])
} // logs 1, 2, 3, each on its own line

Manipulate

Update data

Even if an array is defined as a const its entries are mutable. From our example,

SANDWICH[0] = "houmus";

SANDWICH now has the value

["houmus", 1, true, ["bakery", "home-made"]];

Append data

Onto the end of an array

Use push() method. It takes one or more parameters and "pushes" them onto the end of an array. For instance:

const arr = [1, 2, 3];
arr.push(4);

arr now has the value [1, 2, 3, 4]

Onto the beginning of an array

Use unshift() method. For instance:

const arr = [1, 2, 3];
arr.unshift(0);

arr now has the value [0, 1, 2, 3]

Somewhere specific

Use splice() method.

First argument: the index at which to begin deleting elements
Second argument (optional):  the number of elements to be deleted
Third argument (optional): items to insert starting at that same index, searated by a comma

For instance (example from FreeCodeCamp):

const numbers = [10, 11, 12, 12, 15];
const startIndex = 3;
const amountToDelete = 1;
numbers.splice(startIndex, amountToDelete, 13, 14);
console.log(numbers); // returns [ 10, 11, 12, 13, 14, 15 ]

Append elements from another array

User spread operator (...). For instance (example from FreeCodeCamp):

let arrayToAppend = ['sage', 'rosemary', 'parsley', 'thyme'];
let mainArray = ['basil', 'cilantro', ...arrayToAppend, 'coriander'];

mainArray now has the value ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']

Remove data

From the end of an array

Use pop() method. For instance:

const arr = [1, 2, 3];
arr.pop();

arr now has the value [1, 2]

From the beginning of an array

Use shift() method. For instance:

const arr = [1, 2, 3];
arr.shift();

arr now has the value [2, 3]

Note: removed data can be returned if assigned to a variable. For instance:

const arr = [1, 2, 3];
let removedNumber = arr.pop();
let one = arr.shift();

removedNumber has the number 3 as a value and one, 1

Somewhere specific

You can also use splice() method!

First argument: the index at which to begin deleting elements
Second argument (optional):  the number of elements to be deleted

For instance (from FreeCodeCamp):

let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2); // array now has the value ['today', 'was', 'great']

Here we remove 2 elements, beginning with the third element (at index 2). array would have the value

Note: removed data can be returned if assigned to a variable.

Copy an array

I realized it was not working like classic variables like these:

let a = "first variable"; // a contains "first variable" string
let b = a; // a and b contain "first variable" string
b = "second variable"; // a contains "first variable" and b "second variable" string

let array1 = [1, 2, 3]; // array1 contains [1, 2, 3] array
let array2 = array1; // array1 and array2 contain [1, 2, 3] array
array2.unshift(0); // array1 and array2 contain [0, 1, 2, 3] array

Here, array2 behaves just like another pointer to the same object. Modifying array2 will modify array1 and inversely. So how can we copy an array? Here are several methods:

With spread operator

For instance:

let originalArray = ['great', 'awesome', 'super', 'wonderful'];
let copiedArray = [...originalArray];

originalArray remains unchanged and copiedArray has the same elements as originalArray.

With slice() method

With slice() method, we can copy or extract a given number of elements to a new array, leaving the original array unchanged. It takes 2 parameters:

First argument: the index at which to begin extraction
Second argument (optional):  the index at which to stop extraction (not included)

For instance (example from FreeCodeCamp):

let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3); // todaysWeather is ['snow', 'sleet']