JenMorgan / js-learning

0 stars 0 forks source link

Получить средний возраст #57

Open JenMorgan opened 4 years ago

JenMorgan commented 4 years ago

Напишите функцию getAverageAge(users), которая принимает массив объектов со свойством age и возвращает средний возраст.

Формула вычисления среднего арифметического значения: (age1 + age2 + ... + ageN) / N.

Например:

let vasya = { name: "Вася", age: 25 };
let petya = { name: "Петя", age: 30 };
let masha = { name: "Маша", age: 29 };

let arr = [ vasya, petya, masha ];

alert( getAverageAge(arr) ); // (25 + 30 + 29) / 3 = 28
JenMorgan commented 4 years ago
let vasya = { name: "Вася", age: 25 };
let petya = { name: "Петя", age: 30 };
let masha = { name: "Маша", age: 29 };

let users = [ vasya, petya, masha ];

const getAverage = (arr) => {
    const sum = arr.reduce((sum, current) => sum + current, 0);
    return sum / arr.length;
};

const getInfo = (arr, fn) => arr.map(fn);

const getAge = ({age}) => age;

const arrWithAges = getInfo(users, getAge);
alert( getAverage(arrWithAges) );
JenMorgan commented 4 years ago
const getAverageAge = (arr) => {
    return arr.reduce((sum, user) => sum + user.age, 0) / arr.length
};

alert( getAverageAge(users) );