Menu
Coddy logo textTech

The Reduce Method

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

The reduce() method allows you to "reduce" an array to a single value by executing a provided function for each element of the array. This single value can be a number, string, object, or even another array.

Here is the syntax of the reducer:

array.reduce(function(accumulator, currentValue, currentIndex, array) {
    // return the updated accumulator value
}, initialValue);

Key Components:

  1. accumulator: Accumulates the callback's return values (think of it as the running total)
  1. currentValue: The current element being processed in the array
  1. currentIndex: (optional) The index of the current element
  1. array: (optional) The array reduce() was called upon
  1. initialValue: (optional) A value to use as the first argument to the first call of the callback function

For example - sum of numbers:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15

How It Works Step by Step:

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => {
    console.log(`Accumulator: ${acc}, Current Value: ${curr}`);
    return acc + curr;
}, 0);

// Output:
// Accumulator: 0, Current Value: 1
// Accumulator: 1, Current Value: 2
// Accumulator: 3, Current Value: 3
// Accumulator: 6, Current Value: 4
// Final result: 10
challenge icon

Challenge

Easy

Create a function named calculateGroceryTotal that takes an array of objects representing grocery items.

Each object has two properties:

  • name: string (name of the item)
  • price: number (price of the item)

The function should:

  1. Calculate the total cost of all items
  2. Apply a discount: - If total is above 100, apply 10% discount
  3. If total is above 50 but below or equal to 100, apply 5% discount
  4. No discount for totals of 50 or less.

Return an object containing:

  • originalTotal: the sum before discount
  • discount: the amount saved
  • finalTotal: the final amount after discount

Cheat sheet

The reduce() method reduces an array to a single value by executing a function for each element:

array.reduce(function(accumulator, currentValue, currentIndex, array) {
    // return the updated accumulator value
}, initialValue);

Key Components:

  • accumulator: Accumulates the callback's return values (running total)
  • currentValue: The current element being processed
  • currentIndex: (optional) The index of the current element
  • array: (optional) The array reduce() was called upon
  • initialValue: (optional) Starting value for the accumulator

Example - sum of numbers:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15

Step-by-step execution:

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => {
    console.log(`Accumulator: ${acc}, Current Value: ${curr}`);
    return acc + curr;
}, 0);

// Output:
// Accumulator: 0, Current Value: 1
// Accumulator: 1, Current Value: 2
// Accumulator: 3, Current Value: 3
// Accumulator: 6, Current Value: 4
// Final result: 10

Try it yourself

function calculateGroceryTotal(items) {
    // Write code here
    


    return {
        originalTotal: Math.round(originalTotal * 100) / 100,  // Round to 2 decimals
        discount: Math.round(discount * 100) / 100,
        finalTotal: Math.round(finalTotal * 100) / 100
    };
}
quiz iconTest yourself

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

All lessons in Logic & Flow