Print the oldest poeple

Viewed 81

I have a question. I should write a function which will print the oldest people name from an array and if the date of birth is missing it should count from the current year. I have managed to print the oldest people name but when I write the function for the people whose date of death is missing it prints the wrong name. I have done so far

const people = [
    { name : "Ani", dateBirth: 1970, dateDeath: 2019 },
    { name : "Anna", dateBirth: 1950, dateDeath: 2015 },
    { name : "Ashot", dateBirth: 1550 },
];

function findOldestPeople(people){
    for(let i of people){
        if(!i.hasOwnProperty("dateDeath")){
            let countmissingdate = new Date().getFullYear() - people[2].dateBirth
            console.log(countmissingdate)
            let z = people.sort((a,b)=> b.dateDeath - a.dateBirth)
            document.write("The oldest people is: " + z[0].name)
    }
    }
}
findOldestPeople(people)
<!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>

.

5 Answers

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>

Just use current year if death date isn't available

let z = people.sort((a,b)=> (b.dateDeath || new Date().getFullYear()) - a.dateBirth)

Get the year of today and then minus with the dateBirth if the dateDeath does not exists


let ary = people.sort((a,b)=>{
    (b.dateDeath || new Date().getFullYear) - a.dateBirth)
})

Here is another possible solution without using Array.sort():

const people = [
    { name : "Ani", dateBirth: 1970, dateDeath: 2019 },
    { name : "Anna", dateBirth: 1950, dateDeath: 2015 },
    { name : "Ashot", dateBirth: 1550 },
];

const oldest = people.reduce((o,p,i,a)=>
   (a=(p.dateDeath||new Date().getFullYear())-p.dateBirth)>o[0]?[a,p]:o
   ,[0] );
 console.log("The oldest person is "+oldest[1].name+" (age: "+oldest[0]+").")
<!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>

Notes:

The .reduce() method returns an array for the oldest person: [ age, person_object ].

The fourth parameter a in the callback function will not receive an argument when it is called. I introduced it as a shorthand method for creating a variable with local scope, holding the current age of the current person p.

p.dateDeath||new Date().getFullYear() is a shorthand method for
p.hasOwnProperty("dateDeath") ? p.dateDeath : new Date().getFullYear()

As it has already been pointed out you can use new Date().getFullYear() as the dateDeath of people alive. I would also recommend you to use Array.reduce and split the logic into functions.

const people = [
  { name : 'Ani', dateBirth: 1970, dateDeath: 2019 },
  { name : 'Anna', dateBirth: 1950, dateDeath: 2015 },
  { name : 'Ashot', dateBirth: 1550 },
];
    
const currentYear = new Date ().getFullYear ();
const getAge = ({ dateBirth, dateDeath = currentYear }) => dateDeath - dateBirth;
const keepOlder = (oldest, next) => getAge (oldest) > getAge (next) ? oldest : next;
const findOldest = people => people.reduce (keepOlder);
    
console.log (findOldest (people));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related