How to apply a function simultaneously against two values of the array from left-to-right?

The reduce()

Syntax

array.reduce(callback, initialValue)

Parameters

  • callback ? Function to execute on each value in the array. Takes four arguments: accumulator, currentValue, currentIndex, array.
  • initialValue ? Optional. Object to use as the first argument to the first call of the callback.

Example: Sum Array Elements

<html>
<head>
    <title>JavaScript Array reduce Method</title>
</head>
<body>
    <script>
        var numbers = [1, 2, 3, 4, 5];
        var sum = numbers.reduce(function(accumulator, currentValue) {
            console.log("Accumulator: " + accumulator + ", Current: " + currentValue);
            return accumulator + currentValue;
        }, 0);
        
        document.write("<h3>Sum of array elements: " + sum + "</h3>");
        
        // Without initial value
        var total = [10, 20, 30].reduce(function(a, b) {
            return a + b;
        });
        
        document.write("<p>Total without initial value: " + total + "</p>");
    </script>
</body>
</html>

Example: Finding Maximum Value

<html>
<head>
    <title>Find Maximum with reduce</title>
</head>
<body>
    <script>
        var numbers = [45, 12, 89, 23, 67];
        var max = numbers.reduce(function(prev, current) {
            return (prev > current) ? prev : current;
        });
        
        document.write("<h3>Maximum value: " + max + "</h3>");
        
        // Count occurrences
        var fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
        var count = fruits.reduce(function(acc, fruit) {
            acc[fruit] = (acc[fruit] || 0) + 1;
            return acc;
        }, {});
        
        document.write("<p>Fruit count: " + JSON.stringify(count) + "</p>");
    </script>
</body>
</html>

How It Works

Array.reduce() Process 1 2 3 4 f(1,2)=3 f(3,3)=6 f(6,4)=10 Result: 10

Common Use Cases

Use Case Example Description
Sum/Product [1,2,3].reduce((a,b) => a+b) Mathematical operations
Find Min/Max arr.reduce((a,b) => Math.max(a,b)) Comparison operations
Object Transformation arr.reduce((obj, item) => {...}, {}) Convert arrays to objects

Key Points

  • Without initialValue, the first array element becomes the initial accumulator
  • The callback receives four parameters: accumulator, currentValue, currentIndex, array
  • reduce() processes from left-to-right; use reduceRight() for right-to-left
  • Returns a single value, not an array

Conclusion

The reduce() method is powerful for transforming arrays into single values through iterative processing. It's essential for functional programming patterns and data aggregation tasks.

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

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements