I am trying to find the average of just the females in the given array
sortArray([
{name:'Sarah', gender:'female', age:25},
{name:'Tom', gender:'male', age:18},
{name:'Tim', gender:'male', age:65},
{name:'Kim', gender:'female', age:58}
]);
this is what i have below
function averageFemale(list)
{
let sum = 0;
let femaleCount = 2;
let avg = sum / femaleCount;
for (let i = 0, i < list.length; i++)
{
sum += list[i];
}
return avg;
}
You can filter out "females" to a new array, and then reduce that down to a total of all ages, then use the length of the females array to divide the total by:
const people = [{name:'Sarah', gender:'female', age:25}, {name:'Tom', gender:'male', age:18}, {name:'Tim', gender:'male', age:65}, {name:'Kim', gender:'female', age:58}];
const females = people.filter(person => person.gender === 'female');
const average = females.reduce((total, next) => total + next.age, 0) / females.length;
console.log(average);
const arr= [
{name:'Sarah', gender:'female', age:25},
{name:'Tom', gender:'male', age:18},
{name:'Tim', gender:'male', age:65},
{name:'Kim', gender:'female', age:58}
]
function averageAgeByGender(array,gender){
const getGender = (elem) => elem.gender===gender
const average = (a,b, i, self)=> (a+b.age/self.length)
return array.filter(getGender).reduce(average,0)
}
console.log(averageAgeByGender(arr,'female'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With