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:
- accumulator: Accumulates the callback's return values (think of it as the running total)
- currentValue: The current element being processed in the array
- currentIndex: (optional) The index of the current element
- array: (optional) The array reduce() was called upon
- 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); // 15How 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: 10Challenge
EasyCreate 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:
- Calculate the total cost of all items
- Apply a discount: - If total is above 100, apply 10% discount
- If total is above 50 but below or equal to 100, apply 5% discount
- No discount for totals of 50 or less.
Return an object containing:
originalTotal: the sum before discountdiscount: the amount savedfinalTotal: 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); // 15Step-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: 10Try 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
};
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys