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 function against an accumulator and each key of object in JavaScript?
In JavaScript, we can use the reduce() method to apply a function against an accumulator and each element of an array (from left to right). This method is particularly useful when working with arrays of objects where we need to process each key-value pair.
The reduce() method is called on a given array and takes a callback function as its first argument. Please refer to Array reduce() for more details.
Syntax
array.reduce(callback[, initialValue])
Parameters
callback ? Function to execute on each value in the array.
initialValue ? Object to use as the first argument to the first call of the callback.
The callback function is passed with four arguments:
The first argument is the accumulator, which is the result of the previous callback function call, or the initial value if this is the first call.
The second argument is the current element being processed.
The third argument is the current index being processed.
The fourth argument is the array being processed.
The reduce() method returns the final accumulator value.
Example: Summing Object Values
Let's see how to use reduce() to sum values from an array of objects:
<html>
<head>
<title>Reduce Example</title>
</head>
<body>
<div id="result"></div>
<script>
let arr = [
{ name: "John", value: 5 },
{ name: "Jane", value: 7 },
{ name: "Jim", value: 3 }
];
let sum = arr.reduce((acc, cur) => acc + cur.value, 0);
document.getElementById("result").innerHTML = "Sum: " + sum;
</script>
</body>
</html>
Sum: 15
In this example, we pass a callback function (acc, cur) => acc + cur.value that takes the accumulator acc and current object cur. The function returns the accumulator plus the current object's value property.
Example: Creating Object from Array
Here's how to use reduce() to transform an array into an object:
<html>
<head>
<title>Object Creation Example</title>
</head>
<body>
<div id="result"></div>
<script>
let arr = [
{ name: "John", value: 5 },
{ name: "Jane", value: 7 },
{ name: "Jim", value: 3 }
];
let nameValueMap = arr.reduce((acc, cur) => {
acc[cur.name] = cur.value;
return acc;
}, {});
document.getElementById("result").innerHTML = JSON.stringify(nameValueMap);
</script>
</body>
</html>
{"John":5,"Jane":7,"Jim":3}
Comparison with For Loop
While you can achieve the same result with a for loop, reduce() is more concise:
| Method | Code Length | Readability | Functional Style |
|---|---|---|---|
reduce() |
Shorter | High | Yes |
| For loop | Longer | Medium | No |
<html>
<head>
<title>For Loop Comparison</title>
</head>
<body>
<div id="result"></div>
<script>
let arr = [
{ name: "John", value: 5 },
{ name: "Jane", value: 7 },
{ name: "Jim", value: 3 }
];
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i].value;
}
document.getElementById("result").innerHTML = "Sum using for loop: " + sum;
</script>
</body>
</html>
Sum using for loop: 15
Key Benefits
Immutability:
reduce()doesn't modify the original arrayFunctional programming: Encourages a functional approach to data processing
Flexibility: Can return any data type - numbers, strings, objects, or arrays
Chainable: Can be combined with other array methods like
map()andfilter()
Conclusion
The reduce() method is a powerful tool for processing array elements and their properties sequentially. It provides a clean, functional approach to accumulating values and transforming data structures in JavaScript.
