JavaScript Arrays Cheat Sheet

Fri Aug 25 2023

Let's revise on the arrays in JavaScript.

Array Methods and Loops

This is our array.

let colorArray = ["red", "blue", "orange"]

console.log(colorArray) //(3) ['red', 'blue', 'orange']
Let's access the array's individual elements. We need to type the array name, followed by square brackets with the index number.
console.log(colorArray[0]) //red
Let's change one of the array's elements.

colorArray[0] = "green"

console.log(colorArray) //(3) ['green', 'blue', 'orange']
Let's add an element.

colorArray.push("purple", "black")

console.log(colorArray) //(5) ['green', 'blue', 'orange', 'purple', 'black']
Let's remove an element from the end of the array.

colorArray.pop()

console.log(colorArray) //(4) ['green', 'blue', 'orange', 'purple']
Let's add an element to the beginning of the array.

colorArray.unshift("white")

console.log(colorArray) //(5) ['white', 'green', 'blue', 'orange', 'purple']
Let's remove an element from the beginning of the array.

colorArray.shift()

console.log(colorArray) //(4) ['green', 'blue', 'orange', 'purple']
Let's access the length of the array.

let arrayLength = colorArray.length

console.log(arrayLength) // 4
Let's find the index of an element in the array.

let colorIndex = colorArray.indexOf("orange")

console.log(colorIndex) // 2

let colorIndex = colorArray.indexOf("green")

console.log(colorIndex) // 0
If we're looking for the index of an element that doesn't exist the console will print "-1"

let colorIndex = colorArray.indexOf("gold")

console.log(colorIndex) // -1
Let's loop through the elements of our array.

for(let index = 0; index < colorArray.length; index++) {
___console.log(colorArray[index])
}

// green
blue
orange
purple
OR

for(let everyColor of colorArray) {
___console.log(everyColor)
}

// green
blue
orange
purple
Let's loop through the elements of our array backwards.

for(let index = colorArray.length - 1; index >= 0; index--) {
___console.log(colorArray[index])
}

// purple
orange
blue
green
Let's sort our array (an array of strings) in alphabetical order.

colorArray.sort()

console.log(colorArray) //(4) ['blue', 'green', 'orange', 'purple']
Let's sort our array (an array of strings) in reverse alphabetical order.

colorArray.sort().reverse()

console.log(colorArray) //(4) ['purple', 'orange', 'green', 'blue']

An Array of Arrays

This is an array of warm colors.

let warmColors = ["red", "yellow", "orange"]

This is an array of cool colors.

let coolColors = ["green", "blue", "purple"]

This is an array of all colors.

let allColors = [warmColors, coolColors]

Let's display a list of every color in both arrays.

for (let colors of allColors) {
___ for(let color of colors) {
___ console.log(color)
___ }
}

console.log(color)
// red
yellow
orange
green
blue
purple

Let's access an element inside of an array of arrays. We need to use 2 pairs of square brackets in order to do that. First pair of brackets is the index of the array we want to access. Second pair is the index of the color within the array.

For example, "blue" is the second color (index 1) in the second array (index 1).

console.log(allColors[1][1])//blue

"Red" is the first color (index 0) in the first array (index 0).

console.log(allColors[0][0])//red

"Orange" is the third color (index 2) in the first array (index 0).

console.log(allColors[0][2])//orange

Spread Operator (...)

The spread operator will unpack the elements from within our string and array.

Let's use the spread operator on a string.

let myName = "Lena Esposito"

console.log(myName) //Lena Esposito
console.log(...myName) //L e n a E s p o s i t o

Let's use the spread operator on an array.

let numbers = [1, 2, 3, 4, 5]

console.log(numbers) //(5) [1, 2, 3, 4, 5]
console.log(...numbers) //1 2 3 4 5

Why do we need it? For example, let's find the element with the highest value.
If we use Math.max() without the spread operator, console will print "NaN".

let maximum = Math.max(numbers)

console.log(maximum) //NaN

let maximum = Math.max(...numbers)

console.log(maximum) //5

Rest Parameters (...)

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.

function sum(...numbers) {
___let total = 0;
___for (const number of numbers) {
___total += number;
___}
___return total;
}

console.log(sum(5,10,10)) //25
console.log(sum(5,10,10,15,25)) //65

array.forEach()

Let's capitalize the first letter of each element of an array.

let polishCities = ["warsaw", "gdansk", "torun", "lublin", "katowice"]

This function will capitalize the first letter of the elements of the array.

function capitalize(element, index, array){
___array[index] = element[0].toUpperCase() + element.substring(1);
}

This function will print all the capitalized elements in the console.

function list(element) {
___console.log(element)
}

Let's call both functions.

polishCities.forEach(capitalize)
polishCities.forEach(list)

// Warsaw
Gdansk
Torun
Lublin
Katowice

array.map()

Let's map over every element of an array and execute a callback function on it, and therefore, create a new array.

let unfinishedWords = ["coffe", "latt", "cattl", "mous"]

let finishedWords = unfinishedWords.map(addE)

function addE(element) {
___console.log(element + "e")
}

// cofee
latte
cattle
mouse

array.filter()

Let's check which elements of an array will pass a test provided by a function, and therefore, create a new array.

let age = [3, 5, 15, 25, 35, 36, 45, 11, 101, 8]

let adults = age.filter(adultsCheck)
adults.forEach(print)

function adultsCheck(arrayElement) {
___return arrayElement >= 18;
}

function print(arrayElement){
___console.log(arrayElement)
}

// 25
35
36
45
101

Sorting an array of numbers in ascending or descending order

let age = [3, 5, 15, 25, 35, 36, 45, 11, 101, 8]

function print(element) {
___console.log(element)
}

Let's sort our array of ages in descending order.

aageDesc = age.sort(ageDescending).forEach(print);

function ageDescending(age1, age2) {
___return age2 - age1;
}

// 101
45
36
35
25
15
11
8
5
3

Let's sort our array of ages in ascending order.

ageAsc = age.sort(ageAscending).forEach(print)

function ageAscending(age1, age2) {
___return age1 - age2;
}

//3
5
8
11
15
25
35
36
45
101

array.reduce()

let prices = [3.99, 5.45, 11.99, 104.50]

let total = prices.reduce(addUp)

function addUp(total, element) {
___return total + element
}

console.log("£"+total) //£125.93
Illustration for the JavaScript Arrays Cheat Sheet
Work illustrations by Storyset

Comments (0)


Be the first to leave a comment