Menu
Coddy logo textTech

Chaining Array Methods

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 55 of 65.

Chaining array allows you to perform multiple operations on an array in a single statement. This approach can make your code more concise and readable.

Here's an example of chaining array methods:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const result = numbers
  .filter(num => num % 2 === 0)
  .map(num => num * 2)
  .reduce((sum, num) => sum + num, 0);

console.log(result); // 60

In this example, we start with an array of numbers, filter out the odd numbers, double each remaining number, and then sum up the results.

The order of chaining matters. Each method in the chain operates on the result of the previous method.

challenge icon

Challenge

Easy

Create a function called processFruits that takes an array of fruit objects. Each fruit object has properties name (string) and quantity (number).

The function should use chained array methods to:

  1. Filter out fruits with quantity of 0
  2. Transform each fruit name to uppercase
  3. Create a string that lists all fruits with their quantities like "APPLE: 5, BANANA: 3"

A quick reminder:

You can use the .join(", ") function to convert an array of strings to one single string.

It is possible to chain even the .join() function:

arr.filter(...)
   .map(...)
   .join(...)

Cheat sheet

Chaining array methods allows you to perform multiple operations on an array in a single statement, making code more concise and readable.

Each method in the chain operates on the result of the previous method:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const result = numbers
  .filter(num => num % 2 === 0)
  .map(num => num * 2)
  .reduce((sum, num) => sum + num, 0);

console.log(result); // 60

You can also chain the .join() method to convert an array to a string:

arr.filter(...)
   .map(...)
   .join(", ")

Try it yourself

function processFruits(fruits) {
  // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow