Hello I have an object that I want to browse and when a value is equal to true I fill an array.
My code works but I don’t think it’s good to put so much if.
daysOfWeek: {
lundi: true,
mardi: true,
mercredi: true,
jeudi: false,
vendredi: true,
samedi: true,
dimanche: true
}
let days = []
if (daysOfWeek != null) {
if (daysOfWeek.lundi === true) {
days.push(2)
}
if (daysOfWeek.mardi === true) {
days.push(3)
}
if (daysOfWeek.mercredi === true) {
days.push(4)
}
if (daysOfWeek.jeudi === true) {
days.push(5)
}
if (daysOfWeek.vendredi === true) {
days.push(6)
}
if (daysOfWeek.samedi === true) {
days.push(7)
}
if (daysOfWeek.dimanche === true) {
days.push(1)
}
}
return days
days = [2,3,4,6,7,1]
I tried the switch/case but it doesn’t work for conditions.
Does anyone have another solution for me to explore?
>Solution :
-
I suggest you order and number the days Sunday:0 and Saturday:6 to match JavaScript’s order and numbering. Otherwise add one to the index as I do below.
Note that your example output did not match the object values -
Use reduce:
const daysOfWeek = {
dimanche: true,
lundi: true,
mardi: true,
mercredi: true,
jeudi: false,
vendredi: true,
samedi: true
}
// curr is the true/false. I use && to shortcut and the comma operator to return the accumulator
const days = Object.values(daysOfWeek)
.reduce((acc, curr, index) => (curr && acc.push(index + 1), acc), []);
console.log(days)