-1

I am trying to create a sort of a timetable that also tells me which day someone has a bigger number. The table is working fine, but I cannot 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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
donv13
  • 11
  • 3
  • @zer00ne how is this a duplicate of that question? OP wants to know if the value of a particular property in one object is greater than the corresponding property in another object, not whether the two objects are equal. – Nick Sep 23 '22 at 08:35
  • @Nick if OP had any JavaScript it would be helpful,. – zer00ne Sep 23 '22 at 12:19

2 Answers2

1

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})`))
Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thank you, it works, can you explain the code please; so i can better understand it – donv13 Sep 23 '22 at 23:52
  • @donv13 the code iterates over the entries in `Time` (using `Object.entries`) using `reduce` to build a new object. The values in the object are populated by a `forEach` over the entries in each object in `Time`, making note of the maximum value recorded on each day and the person who had that maximum. It also stores the value for each person for each day in that accumulator. I would highly recommend adding `console.log(days)` after the reduce to see the structure that has been built up. The final `forEach` then prints the maximum values for each day. – Nick Sep 24 '22 at 01:12
0

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'