Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to apply a function simultaneously against two values of the array from left-to-right?
The The reduce()
Syntax
array.reduce(callback, initialValue)
Parameters
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
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
Conclusion
reduce() method is powerful for transforming arrays into single values through iterative processing. It's essential for functional programming patterns and data aggregation tasks.
