How to reduce arrays in JavaScript?

The reduce() method transforms an array into a single value by applying a function to each element. It's commonly used for calculations like summing numbers, finding maximums, or combining data.

Syntax

array.reduce(callback(accumulator, currentValue, index, array), initialValue)

Parameters:

  • callback - Function executed on each element
  • accumulator - Accumulated result from previous iterations
  • currentValue - Current element being processed
  • initialValue (optional) - Starting value for accumulator

Example: Summing Array Elements

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Reduce Example</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .result {
            font-size: 18px;
            font-weight: 500;
            color: blueviolet;
            margin: 10px 0;
        }
        .sample {
            font-size: 18px;
            font-weight: 500;
            color: red;
            margin: 10px 0;
        }
        button {
            padding: 8px 16px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>Reduce Arrays in JavaScript</h1>
    <div class="sample">Array: [1, 3, 5, 6, 9, 22, 15]</div>
    <button class="sum-btn">Calculate Sum</button>
    <div class="result"></div>
    
    <script>
        let resEle = document.querySelector(".result");
        let btnEle = document.querySelector(".sum-btn");
        let arr = [1, 3, 5, 6, 9, 22, 15];
        
        btnEle.addEventListener("click", () => {
            let sum = arr.reduce((accumulator, currentValue) => {
                return accumulator + currentValue;
            }, 0);
            resEle.innerHTML = `Sum = ${sum}`;
        });
    </script>
</body>
</html>

Using reduce() for Different Operations

Here are common patterns using reduce():

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reduce Operations</title>
</head>
<body>
    <h1>Array Reduce Operations</h1>
    <div id="output"></div>
    
    <script>
        const numbers = [1, 3, 5, 6, 9, 22, 15];
        const output = document.getElementById('output');
        
        // Sum
        const sum = numbers.reduce((acc, num) => acc + num, 0);
        
        // Product
        const product = numbers.reduce((acc, num) => acc * num, 1);
        
        // Maximum value
        const max = numbers.reduce((acc, num) => Math.max(acc, num));
        
        // Count even numbers
        const evenCount = numbers.reduce((acc, num) => {
            return num % 2 === 0 ? acc + 1 : acc;
        }, 0);
        
        output.innerHTML = `
            <p>Array: [${numbers.join(', ')}]</p>
            <p>Sum: ${sum}</p>
            <p>Product: ${product}</p>
            <p>Maximum: ${max}</p>
            <p>Even numbers count: ${evenCount}</p>
        `;
    </script>
</body>
</html>

How reduce() Works

The reduce() method processes each array element from left to right, accumulating results:

  1. Starts with initial value (or first element if no initial value)
  2. Calls callback function for each element
  3. Passes the accumulated result to the next iteration
  4. Returns the final accumulated value

Common Use Cases

Operation Example Initial Value
Sum (acc, num) => acc + num 0
Product (acc, num) => acc * num 1
Concatenate (acc, str) => acc + str ""
Object from array (acc, item) => ({...acc, [item.id]: item}) {}

Conclusion

The reduce() method is powerful for transforming arrays into single values. Always provide an initial value to avoid unexpected behavior with empty arrays.

Updated on: 2026-03-15T23:18:59+05:30

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements