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?
2
Answers
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:
I agree with this answer suggestion.
The number must be from
0
(Sunday) to6
(Saturday).In some locales, it may be
0
(Monday) to6
(Sunday).moment weekday
But if you want to set
1
as the first day of the week, I would suggest the code below