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?
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})`))
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'