- Joined
- Dec 7, 2022

- Messages
- 5

- Reaction score
- 0

You are given an array years that contains years of life of different people in the next format 1714-1748 (year of birth - year of death).

Write a function getAverageAge returning an average life duration of all the people rounding it to the nearest whole (Math.round)

Example:

getAverageAge(['1832-1905', '1876-1956', '1683-1724', '1714-1748']) === 57

getAverageAge([ '1907-1997', '1761-1833', '1535-1582', '1918-2012', '1877-1968', '1696-1724', '1602-1642', '1692-1743', '1695-1762', '1570-1636', '1762-1807', '1668-1731', ]) === 63

I've been struggling with this function the whole day with no succes.

Before implementing the math in order to return the average age I've been trying to get the years in an array, but I can't find a way to convert the string into numbers.

This function just returns the first digit after '-', ex: console.log(getAverageAge('7111-4222')); - returns '4'

function getAverageAge(years) {

let arr = [];

for(let i = 0; i <= years.length; i++){

if(years

*=== '-'){*

arr.push(years[i + 1]);

};

};

return arr;

}

And this function returns undefinded:

function getAverageAge(years) {

let number = Number(years); ---also tryed let number = +years---

let arr = [];

for(let i = 0; i <= number.length; i++){

if(number

arr.push(years[i + 1]);

};

};

return arr;

}

And this function returns undefinded:

function getAverageAge(years) {

let number = Number(years); ---also tryed let number = +years---

let arr = [];

for(let i = 0; i <= number.length; i++){

if(number

*=== '-'){*

arr.push(number[i + 1]);

}else{

arr.push(numberarr.push(number[i + 1]);

}else{

arr.push(number

*);*

}

return arr;

}

}

I'm lost please help !}

return arr;

}

}

I'm lost please help !