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
Selected Reading
How to iterate over objects in array and sum a property in JavaScript
Suppose we have an array of objects like this:
const arr = [
{
duration: 10,
any: 'fields'
}, {
duration: 20,
any: 'other fields'
}, {
duration: 15,
any: 'some other fields'
}
];
We are required to write a JavaScript function that takes in one such array and returns the summed result of the duration properties of all the objects.
For the above array, the output should be 45.
Using for Loop
The traditional approach uses a for loop to iterate through the array and accumulate the sum:
const arr = [
{
duration: 10,
any: 'fields'
}, {
duration: 20,
any: 'other fields'
}, {
duration: 15,
any: 'some other fields'
}
];
const addDuration = arr => {
let res = 0;
for(let i = 0; i
45
Using reduce() Method
A more concise approach uses the reduce() method to sum the property values:
const arr = [
{ duration: 10, any: 'fields' },
{ duration: 20, any: 'other fields' },
{ duration: 15, any: 'some other fields' }
];
const sumDuration = arr => {
return arr.reduce((total, obj) => total + obj.duration, 0);
};
console.log(sumDuration(arr));
45
Using forEach() Method
Another approach uses forEach() to iterate and accumulate:
const arr = [
{ duration: 10, any: 'fields' },
{ duration: 20, any: 'other fields' },
{ duration: 15, any: 'some other fields' }
];
const calculateSum = arr => {
let sum = 0;
arr.forEach(obj => {
sum += obj.duration;
});
return sum;
};
console.log(calculateSum(arr));
45
Comparison
| Method | Readability | Performance | Functional Style |
|---|---|---|---|
| for loop | Good | Fast | No |
| reduce() | Excellent | Good | Yes |
| forEach() | Good | Good | Partial |
Conclusion
The reduce() method is the most concise and functional approach for summing object properties. Use for loops when performance is critical or forEach() for better readability over traditional loops.
Advertisements
