What is reduce() in JavaScript

1. What is reduce()?

The reduce() method in JavaScript is used to “reduce” an array into a single value by running a function on each element of the array.

This single value could be:

  • A number (sum, product, average, etc.)

  • A string (concatenated sentence, joined names, etc.)

  • An object (grouped data, frequency count, etc.)

  • Even another array (flattening arrays, etc.)

Think of reduce() as:

"Take my array, go through it one item at a time, and keep combining the result until I have only one thing left."

Here’s a visual diagram showing how reduce() processes each step — starting from the initialValue and updating the accumulator after adding each array element. This makes it easier to see the flow from start to finish.


2. Syntax

array.reduce(callbackFunction, initialValue);

Parameters

  1. callbackFunction → The function that runs on each element.

    • It takes 4 arguments:

      function(accumulator, currentValue, currentIndex, array)
      
      • accumulator → The value that carries over between each loop.

      • currentValue → The current element being processed.

      • currentIndex → The index of the current element (optional).

      • array → The original array (optional).

  2. initialValue → (optional but highly recommended) The starting value for the accumulator.


3. How it works step-by-step

Let’s start with a simple example — summing numbers.

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

console.log(sum); // 15

Step-by-step execution:

  • Step 1: Initial accumulator = 0 (from initialValue)

  • Step 2: Add first number → 0 + 1 = 1

  • Step 3: Add second number → 1 + 2 = 3

  • Step 4: Add third number → 3 + 3 = 6

  • Step 5: Add fourth number → 6 + 4 = 10

  • Step 6: Add fifth number → 10 + 5 = 15

  • Final Result: 15


4. Using Arrow Function

const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15

Here:

  • acc = accumulator

  • curr = current value


5. More Examples

Example 1: Find Maximum Value

const numbers = [10, 25, 30, 5, 40];

const max = numbers.reduce((acc, curr) => {
  return curr > acc ? curr : acc;
}, numbers[0]);

console.log(max); // 40

Example 2: Count Occurrences

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});

console.log(count);
// { apple: 3, banana: 2, orange: 1 }

Example 3: Flatten an Array

const nested = [[1, 2], [3, 4], [5, 6]];

const flat = nested.reduce((acc, curr) => acc.concat(curr), []);

console.log(flat); // [1, 2, 3, 4, 5, 6]

Example 4: Sum of Object Values

const items = [
  { name: 'Book', price: 200 },
  { name: 'Pen', price: 50 },
  { name: 'Bag', price: 500 }
];

const total = items.reduce((acc, item) => acc + item.price, 0);

console.log(total); // 750

6. Common Mistakes Beginners Make

❌ Forgetting to set the initialValue (can cause unexpected results if the array is empty).
❌ Confusing accumulator with currentValue.
❌ Thinking reduce() only works for numbers (it works for any data type!).


7. Why Use reduce()?

  • It’s powerful: Can replace many for or forEach loops.

  • It’s flexible: Works with numbers, strings, objects, arrays.

  • It’s cleaner: Keeps logic in one place.

No comments:

Post a Comment

What is slice() in JavaScript

What is slice() ? slice() is a method used to copy a portion of an array or string without changing the original . Think of it like cut...