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
Finding average age from array of Objects using JavaScript
Problem
We need to write a JavaScript function that takes an array of objects containing people's data and calculates the average age from the age property.
Example
Following is the code:
const people = [
{ fName: 'Ashish', age: 23 },
{ fName: 'Ajay', age: 21 },
{ fName: 'Arvind', age: 26 },
{ fName: 'Mahesh', age: 28 },
{ fName: 'Jay', age: 19 },
];
const findAverageAge = (arr = []) => {
const { sum, count } = arr.reduce((acc, val) => {
let { sum, count } = acc;
sum += val.age;
count++;
return { sum, count };
}, {
sum: 0,
count: 0
});
return (sum / (count || 1));
};
console.log(findAverageAge(people));
Output
23.4
Method 1: Using reduce() (Recommended)
The above example uses reduce() to accumulate both sum and count. Here's a simpler version:
const people = [
{ fName: 'Ashish', age: 23 },
{ fName: 'Ajay', age: 21 },
{ fName: 'Arvind', age: 26 },
{ fName: 'Mahesh', age: 28 },
{ fName: 'Jay', age: 19 }
];
const findAverageAge = (arr) => {
const totalAge = arr.reduce((sum, person) => sum + person.age, 0);
return totalAge / arr.length;
};
console.log(findAverageAge(people));
23.4
Method 2: Using for...of Loop
const people = [
{ fName: 'Ashish', age: 23 },
{ fName: 'Ajay', age: 21 },
{ fName: 'Arvind', age: 26 },
{ fName: 'Mahesh', age: 28 },
{ fName: 'Jay', age: 19 }
];
const findAverageAge = (arr) => {
let totalAge = 0;
for (const person of arr) {
totalAge += person.age;
}
return totalAge / arr.length;
};
console.log(findAverageAge(people));
23.4
Method 3: Using map() and reduce()
const people = [
{ fName: 'Ashish', age: 23 },
{ fName: 'Ajay', age: 21 },
{ fName: 'Arvind', age: 26 },
{ fName: 'Mahesh', age: 28 },
{ fName: 'Jay', age: 19 }
];
const findAverageAge = (arr) => {
const ages = arr.map(person => person.age);
const sum = ages.reduce((total, age) => total + age, 0);
return sum / ages.length;
};
console.log(findAverageAge(people));
23.4
Handling Empty Arrays
For robust code, handle empty arrays to avoid division by zero:
const findAverageAge = (arr) => {
if (arr.length === 0) {
return 0;
}
const totalAge = arr.reduce((sum, person) => sum + person.age, 0);
return totalAge / arr.length;
};
console.log(findAverageAge([])); // Empty array
console.log(findAverageAge([{ fName: 'John', age: 25 }])); // Single person
0 25
Comparison
| Method | Readability | Performance | Lines of Code |
|---|---|---|---|
| reduce() only | High | Good | 2 |
| for...of loop | Medium | Best | 5 |
| map() + reduce() | High | Lower | 3 |
Conclusion
The reduce() method provides the cleanest solution for calculating average age from an array of objects. Always handle edge cases like empty arrays for production code.
Advertisements
