Conteúdo do curso
JavaScript Course for Beginners: Fundamentals and Practice
Sobre a Aula

Iteration in Arrays with forEach, map, filter, and reduce

Congratulations on reaching the final lesson of Module 4! In this concluding stage, you will master advanced array iteration techniques in JavaScript, using methods like forEach, map, filter, and reduce.

Prepare to learn how to perform complex tasks with greater efficiency and readability, elevating your proficiency in the language.

forEach

The forEach method is a convenient way to iterate over all elements of an array and perform an action on each of them.

It’s like an “inspector” visiting each house on a street, checking and doing something in each one.

Imagine we have an array called “houses” containing various houses on a street. Using forEach, we can walk down the street and visit each house individually.

During each visit, we can perform an action, such as knocking on the door, delivering mail, or checking if anyone is inside.

In code, we use the forEach method with a function as an argument. This function will be executed for each element of the array.

Inside this function, we can perform desired actions, such as displaying the house number in the console or changing a specific property.

It’s important to note that forEach does not return a new array; it only traverses the existing array.

If we want to create a new array based on the transformations made to each element, we should use other methods, such as map.

Using forEach allows us to avoid traditional “for” loops and make our code more readable and concise.

It is a useful tool for performing operations on each item in the array without worrying about the details of iteration.

Here’s a simple example of using forEach:

const houses = ["House 1", "House 2", "House 3", "House 4"];
houses.forEach((house, index) => {
  console.log(`Visiting ${house}`);
  console.log(`Index: ${index}`);
});

In this example, we have an array called “houses” with four elements. We use the forEach method to iterate over each element of the array.

Inside the callback function passed to forEach, we receive two parameters: house and index.

The variable house represents each element of the array as it is traversed, and the variable index represents the index of that element.

In the body of the function, we are displaying a message in the console for each visited house along with its index.

Executing this code would result in the following output:

Visiting House 1
Index: 0

Visiting House 2
Index: 1

Visiting House 3
Index: 2

Visiting House 4
Index: 3

We can perform various actions within the callback function, such as accessing specific properties of array elements, performing calculations, or modifying values.

forEach allows us to iterate over elements in a simplified way, making the code more readable and expressive.

So, think of forEach as an inspector visiting each array element, allowing you to execute custom actions during each visit.

It simplifies array iteration and facilitates data processing.

map

The map method is used in JavaScript arrays to create a new array based on an existing one.

It iterates over each element of the original array and applies a callback function to each of these elements, returning a new value. The resulting new array will have the same size as the original array.

We can make an analogy with a production process in a factory. Imagine we have a conveyor belt with various wooden pieces, and we need to turn each of these pieces into custom furniture.

The map method would be like a set of tools we use to shape each piece and transform them into custom furniture.

The callback function we pass to map would be like the tools we use in this process.

It receives each element of the original array, performs some operation or transformation on it, and returns the result.

Let’s see an example to illustrate:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => {
  return number * 2;
});

console.log(doubled);

In this example, we have an array called numbers with five elements. We use the map method to create a new array called doubled. The callback function multiplies each number by 2, returning the result.

Executing this code would result in:

[2, 4, 6, 8, 10]

We can see that each element of the original array has been doubled, resulting in a new array with doubled values.

The map method is useful when we need to transform an array into another based on a specific rule or operation.

It allows us to work more concisely and expressively, simplifying the code and making it more readable.

It’s important to remember that map does not alter the original array but creates a new array with the results of the transformations. This ensures that no unwanted side effects occur.

filter

The filter method is used in JavaScript arrays to create a new array containing only the elements that meet a specific condition.

It iterates over each element of the original array and checks if it satisfies the condition specified in a callback function. If the condition is true, the element is added to the resulting new array.

We can make an analogy with selecting fruits at a market. Imagine we have a basket full of different fruits, and we need to select only the ripe fruits.

The filter method would be like a magical filter that analyzes each fruit and separates only the ripe ones into a new basket.

The callback function we pass to filter would be like the ripeness rule we use in this process.

It receives each element of the original array, checks if it meets the ripeness condition, and returns a Boolean value (true or false).

Let’s see an example to illustrate:

const fruits = ["apple", "banana", "orange", "grape", "pineapple"];
const ripeFruits = fruits.filter((fruit) => {
  return fruit === "banana" || fruit === "orange";
});

console.log(ripeFruits);

In this example, we have an array called fruits with five elements.

We use the filter method to create a new array called ripeFruits. The callback function checks if each fruit is equal to “banana” or “orange.”

If the condition is true, the fruit is added to the new array.

Executing this code would result in:

["banana", "orange"]

We can see that only the “banana” and “orange” fruits were selected since they are the only ones that meet the ripeness condition.

The filter method is useful when we need to filter the elements of an array based on a specific condition.

It allows us to obtain a subset of elements that are relevant to our logic or need.

It’s essential to highlight that filter does not alter the original array but creates a new array containing the filtered elements. This preserves the integrity of the original array and allows us to work with the results safely.

reduce

The reduce method is used in JavaScript arrays to perform a reduction of elements to a single value.

It iterates over each element of the array and, in each iteration, combines the current element with an accumulator, producing a single output value.

The final result is this accumulated value after traversing all elements of the array.

We can make an analogy with counting the total number of pages in a book.

Imagine you have a book with several pages, and you want to know how many pages it has.

The reduce method would be like a counter that you use to add up the number of pages one by one.

For each page you turn, you add the page number to the counter. In the end, you get the total number of pages in the book.

In JavaScript, we use a callback function that is executed in each iteration of reduce.

This function receives two parameters: the accumulator and the current element of the array.

It combines these values in some way and returns the result of this combination, which becomes the new value of the accumulator.

Let’s see an example to illustrate:

const numbers = [1, 2, 3, 4, 5];
const totalSum = numbers.reduce((accumulator, number) => {
  return accumulator + number;
}, 0);

console.log(totalSum);

In this example, we have an array called numbers with five elements. We use the reduce method to obtain the total sum of these numbers.

The callback function receives the accumulator (starting with an initial value of 0) and each number from the array. It returns the sum of the accumulator and the current number.

Executing this code would result in:

15

We can see that the total sum of the array numbers is 15. This is because reduce traversed each element of the array, adding it to the accumulator.

The reduce method is useful when we need to perform reduction operations on an array, such as getting the sum, average, maximum, or minimum of the elements.

It allows us to combine values in a custom way, according to our logic, and obtain a single result.

It’s important to mention that reduce can receive an optional initial value as the last argument. This value will be the initial value of the accumulator.

If not provided, the first element of the array will be used as the initial value.

Remember that reduce does not alter the original array but produces a single resulting value. This allows us to work with the result safely and maintain the integrity of the original array.

Challenge

  • Create a JavaScript script that creates an array with the names of products in a store and their prices.
  • Use the map method to transform the prices into numbers.
  • Use the filter method to select only the products with a price above R$ 100.00.
  • Use the reduce method to calculate the total purchase amount for the selected products.

Congratulations on completing the lesson, where you learned about forEach, map, filter, and reduce concepts. So, practice what you learned in this module to master this concept.

This module contains some of the most commonly used content in JavaScript, so review the lessons until you grasp the content. Once you’ve mastered the topic, you can move on to the next module.

Entrar na conversa
Rolar para cima