JavaScript Array Methods - Iterations

JavaScript Array Methods - Iterations

Introduction

This is the fourth article in the JavaScript Array Methods series — a series created to introduce beginners to array methods, their syntax, and usage. In this article, we will discuss the array methods that are used for iteration in an array and their differences. Iteration simply means repeating a set of instructions till a condition is met.

Prerequisites

It'll be great to read the introductory article. It gives a quick overview of array methods and why they're important. You can also check out other array methods in the series.

forEach()

The forEach() array method is used to call a function once for each item in the array. It requires a callback function (i.e. the function to be executed for each item) as an argument. The callback function can take three arguments for the following parameters:

  • item - represents each item in the array

  • index - the index of the item

  • array - the array on which the forEach method is called (this parameter is rarely used)

The return value for forEach() is always undefined.

Syntax:

array.forEach((item) => {/*some code to execute*/})
array.forEach((item, index) => {/*some code to execute*/})
array.forEach((item, index, array) => {/*some code to execute*/})

Usage:

const nums = [2, 8, 1, 9, 10]

nums.forEach(num => console.log(num * 2)) 

/** 
* Output :
* 4
* 16
* 1
* 18
**/                        

const countries = ["Ghana", "Nigeria", "Kenya"]

countries.forEach((country, index) => {
    console.log(`${country} is at index ${index}`)
})

/** 
* Output :
* Ghana is at index 0
* Nigeria is at index 1
* Kenya is at index 2
**/

map()

The map() method is used to call a function for each item in an array, similar to forEach(). However, the key difference is that while forEach() returns undefined, map() returns a new array with the results obtained from calling the provided function on each item.

Syntax:

array.map((item) => {/*some code to execute*/})
array.map((item, index) => {/*some code to execute*/})
array.map((item, index, array) => {/*some code to execute*/})

Usage:

const totalScores = [420, 501, 300, 560, 480]

const avgScores = totalScores.map(score => score / 6)
console.log(avgScores) // [70, 83.5, 50, 93.33333333333333, 80]

filter()

As the name suggests, this method is used to filter out items in an array based on whether a condition is true or false. It follows a similar syntax as map() and forEach() where it takes a callback function (which will contain the condition) as an argument.

Syntax:

array.map((item) => {/*some code to execute*/})
array.map((item, index) => {/*some code to execute*/})
array.map((item, index, array) => {/*some code to execute*/})

Usage:

const age = [25, 16, 18, 21, 14, 35, 13]

const legalAge = age.filter(ageItem => ageItem >= 18)
console.log(legalAge) // [25, 18, 21, 35]

In this example, we are filtering out ages that are legal, i.e. ages greater than or equal to 18. filter() will test the condition (ages greater than 18) against each item in the array and return the items that pass the condition.

reduce()

The reduce() method can be used to reduce items in an array to a single value. It does not modify the original array. It takes in a callback function and an initial value as arguments. The callback function has all the following parameters

  • accumulator - represents the accumulated results from the previous execution of the function.

  • current item - the current item in the array that the function is being performed on.

  • current index - the index of the current item

  • array - the array on which the method is called (this parameter is rarely used)

The initial value as an argument is optional. It represents the value that is initially used as the accumulator. If it is not specified, the accumulator starts as the first item in the array.

Syntax:

array.reduce((accumulator, currentItem) => {/*some code to execute*/}, initialValue))
array.reduce((accumulator, currentItem, currentIndex) => {/*some code to execute*/}, initialValue))
array.reduce((accumulator, currentItem, currentIndex, array) => {/*some code to execute*/}, initialValue))

Usage:

const testScores = [98, 85, 87, 90, 95, 88]

// without initial value
const totalScore1 = testScores.reduce((accumulator, currentItem) => {
    return accumulator + currentItem
})

// with initial value
const totalScore2 = testScores.reduce((accumulator, currentItem) => {
    return accumulator + currentItem
}, 10)

console.log(totalScore1) // 543
console.log(totalScore2) // 553

In this example, we are finding the total score of test scores using the reduce() method.

In totalScore1, an initial value is not specified so the accumulator is initialized as the first item in the array, i.e. 98

In totalScore2, the initial value is specified as 10, which becomes the accumulator's initial value.

When to use each array iteration method.

As you have seen, these methods are similar and it can be confusing to figure out when to use them.

  • Use forEach() if you want to perform an execution on each item in the array and would not need an array of the new values after the execution.

  • Use map() if you would need to use the transformed array after the function execution or would need to chain other array methods. For example:

const nums = [2, 5, 3, 1, 9]

const newNums = nums.map(num => num * 2).sort().reverse()
console.log(newNums) // [ 6, 4, 2, 18, 10 ]

You cannot chain other array methods to forEach() because its return value is undefined.

If the output of the example is confusing, check out my other article in this series that explains how sort() and reverse() work.

  • Use filter() when you want to filter out some items in an array based on a condition. I find myself using filter() a lot when I have to create a delete function.

    For example, I built a post web app project in React, where you can add, edit and delete a post. I used filter() in the delete function to delete posts. Code below:

   function deletePost(id) {
        setFeed(prevFeed => prevFeed.filter(post => post.id !== id))
        setOverlay(false)
    }

In the function, I am filtering out posts that do not match the id that was clicked. This means filter() will return an array without the post that has its id matching.

  • Use reduce() when you need to have a single value after a function execution of each item in the array.

Conclusion

Congrats on making it this far!
In this article, we discussed the various array methods used for executing functions on each array item: forEach(), map(), filter() and reduce()

We also discussed when using one over the other is more efficient.

Thanks for reading!