JavaScript Array Methods

Let’s spend a bit of time going over some common array methods in Javascript.

forEach

As the name implies, this loops over items in an array.

const fruits = ["Apples", "Oranges", "Kiwis"]

// As a regular function
fruits.forEach(function(fruit, index) {
    console.log(fruit)
})

// As an arrow function
fruits.forEach((fruit, index) => console.log.(fruit))

// This will return...
Apples
Oranges
Kiwis

Moving forward we will only use arrow functions.

map

Map works in a similar way to forEach except that it returns an array, with the ability to change each item in the array. For example, here we change each array item to uppercase.

fruits.map((fruit) => fruit.toUpperCase());

// This will return...
["APPLES", "ORANGES", "KIWIS"]

filter

Filter allows us to define a… filter.. which determines which array items are returned in a new array. For example, we may only want to return fruits which begin with an A.

fruits.filter((fruit) => fruit[0] === 'A');

// This will return...
Apples

reduce

Reduce applies a function to each element and reduces the array to a single value. We can use this if we have an array of numbers and we wish to find the sum.

numbers = [5, 10, 15,20]

numbers.reduce((total, number) => total + number);

// This will return...
50

spread

Spread essentially allows us to insert one array into another in a way which doesn’t result in nested arrays. For example, if we return to our fruits array, let’s say we needed another array but wanted to have it contain the values in the first.

Spread is activated with ... within an array.

let newFruits = [...fruits, "Mangoes", "Peaches"]

// This will return...
(5) ["Apples", "Oranges", "Kiwis", "Mangoes", "Peaches"]

Without using spread, we would end up with a nested array.

newFruits = [fruits, "Mangoes", "Peaches"]

// This will return...
(3) [Array(3), "Mangoes", "Peaches"]

Spread can also be used with objects where an object can be replicated while having additional properties or methods added.