Home > Blockchain >  How can i compare which object property is bigger?
How can i compare which object property is bigger?

Time:09-23

I am trying to create sort of a timetable that also tells me which day someone has a bigger number, the table is working fine but i can not figure out how to compare each day without doing a lot of if's, this is my code below (the table and the object)

let Time = {
  Person1: {
    Monday: 9,
    Tuesday: 7,
    Wednesday: 8,
    Thursday: 7,
    Friday: 7,
  },
  Person2: {
    Monday: 8,
    Tuesday: 8,
    Wednesday: 7,
    Thursday: 7,
    Friday: 9,
  },
};

console.table(Time);
I want it to display 'Person 2' if monday from person 1 is smaller than monday from person 2 (for each day), can i do that?

CodePudding user response:

My approach would be using ternary on each days

let Time = {
  Person1: {
    Monday: 9,
    Tuesday: 7,
    Wednesday: 8,
    Thursday: 7,
    Friday: 7,
  },
  Person2: {
    Monday: 8,
    Tuesday: 8,
    Wednesday: 7,
    Thursday: 7,
    Friday: 9,
  },
};

console.log(Time.Person1.Monday < Time.Person2.Monday ? 'Person 1' : 'Person 2') 

The code above will return 'Person 2'

CodePudding user response:

You could use a combination of reduce and forEach to iterate the values in Time to collect the maximum value and name of the associated person for each day:

let Time = {
  Person1: { Monday: 9, Tuesday: 7, Wednesday: 8, Thursday: 7, Friday: 7 },
  Person2: { Monday: 8, Tuesday: 8, Wednesday: 7, Thursday: 7, Friday: 9 }
};

const days = Object.entries(Time).reduce((acc, [name, person]) => {
  Object.entries(person).forEach(([day, value]) => {
    acc[day] = acc[day] || { max: { value: 0, name: '' } }
    acc[day][name] = value             // not strictly required
    if (value > acc[day].max.value) {
      acc[day].max = { value, name }
    }
  });
  return acc
}, {})

Object.entries(days).forEach(([day, data]) => console.log(`${day}: ${data.max.name} (${data.max.value})`))

  • Related