Home > Enterprise >  why if statement gives wrong value?
why if statement gives wrong value?

Time:09-04

Exercise 12 - Find the Oldest

Given an array of objects representing people with a birth and death year, return name the oldest person.

Hints

  • this can be done with a couple of chained array methods, or by using reduce.

I want to use reduce method

const people = [
  {
    name: 'Carly',
    yearOfBirth: 1942,
    yearOfDeath: 1970,
  },
  {
    name: 'Ray',
    yearOfBirth: 1962,
    yearOfDeath: 2011,
  },
  {
    name: 'Jane',
    yearOfBirth: 1912,
    yearOfDeath: 1941,
  },
];

const findTheOldest = function (arr) {
  const oldestPerson = arr.reduce((accumulator, next) => {
    const age1 = accumulator.yearOfDeath - accumulator.yearOfBirth;
    const age2 = next.yearOfDeath - next.yearOfBirth;

    if (age1 > age2) {
      return accumulator.name;
    } else {
      return next.name;
    }
  });
  return oldestPerson;
};

console.log(findTheOldest(people));

CodePudding user response:

Just slightly corrected your code

const people = [
  {name: 'Carly', yearOfBirth: 1942, yearOfDeath: 1970,},
  {name: 'Ray', yearOfBirth: 1962, yearOfDeath: 2011,},
  {name: 'Jane', yearOfBirth: 1912, yearOfDeath: 1941,},
];

const findTheOldest = function (arr) {
  if (arr.length === 0) return null;
  if (arr.length === 1) return arr[0].name;
  
  const getAge = ({ yearOfDeath, yearOfBirth }) => yearOfDeath - yearOfBirth;
  
  const oldestPerson = arr.reduce((acc, next) => (getAge(acc) > getAge(next)) ? acc : next);
  
  return oldestPerson.name;
};

console.log(findTheOldest(people));
.as-console-wrapper { max-height: 100% !important; top: 0 }

CodePudding user response:

Now it works fine.

const people = [
  {
    name: 'Carly',
    yearOfBirth: 1942,
    yearOfDeath: 1970,
  },
  {
    name: 'Ray',
    yearOfBirth: 1962,
    yearOfDeath: 2011,
  },
  {
    name: 'Jane',
    yearOfBirth: 1912,
    yearOfDeath: 1941,
  },
];

const findTheOldest = function (arr) {
  const oldestPerson = arr.reduce((accumulator, next) => {
    const age1 = accumulator.yearOfDeath - accumulator.yearOfBirth;
    const age2 = next.yearOfDeath - next.yearOfBirth;

    if (age1 > age2) {
      return accumulator;
    } else {
      return next;
    }
  });
  return oldestPerson.name;
};

console.log(findTheOldest(people));

  • Related