Issue
The problem is that you calculate the age of the person who has no deathDate but you don't use it anywhere.
Note: Avoid hardcoded indices like you did in the loop people[2].dateBirth
you can use the indice like i.dateBirth
in the for of loop
Solution
- Calculate for all the people the age's when there is no dateDeath property take the current year as you did.
- Push the name and the age to an array.
- Sort this array by age in descending order and get the oldest one by taking the first element of the array.
const people = [{
name: "Ani",
dateBirth: 1970,
dateDeath: 2019
},
{
name: "Anna",
dateBirth: 1950,
dateDeath: 2015
},
{
name: "Ashot",
dateBirth: 1550
},
];
const temp = []
function findOldestPeople(people) {
for (let i of people) {
if (!i.hasOwnProperty("dateDeath")) {
let age = new Date().getFullYear() - i.dateBirth;
console.log(age);
temp.push({
name: i.name,
age: age
});
}else{
let age = i.dateDeath - i.dateBirth;
temp.push({
name: i.name,
age: age
});
}
temp.sort((a, b) => b.age - a.age )
}
return temp[0];
}
const oldestOne = findOldestPeople(people);
document.write("The oldest people is: " + oldestOne.name)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script src="script.js"></script>
</html>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…