Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find average of an array of objects

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;
}
like image 986
Jayson G Avatar asked Nov 01 '18 17:11

Jayson G


2 Answers

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);
like image 198
KevBot Avatar answered Oct 03 '22 11:10

KevBot


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'))
like image 37
Enrique Briones Arcos Avatar answered Oct 03 '22 11:10

Enrique Briones Arcos