skip to Main Content

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


    1. 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

    2. 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)
    Login or Signup to reply.
  1. I agree with this answer suggestion.

    The number must be from 0 (Sunday) to 6 (Saturday).
    In some locales, it may be 0 (Monday) to 6 (Sunday).

    moment weekday

    But if you want to set 1 as the first day of the week, I would suggest the code below

    const daysOfWeek =  {
      lundi: true,
      mardi: true,
      mercredi: true,
      jeudi: false,
      vendredi: true,
      samedi: true,
      dimanche: true
    }
    
    const TOTAL_DAYS_OF_WEEK = 7;
    const IS_SUNDAY_A_FIRST_DAY_OF_WEEK = true;
    const FIRST_DAY_START_WITH = 1;
    
    const result = [];
    Object.values(daysOfWeek).forEach((value, index) => {
        if(value) {
            const dayOfWeek = (index + IS_SUNDAY_A_FIRST_DAY_OF_WEEK) % TOTAL_DAYS_OF_WEEK + FIRST_DAY_START_WITH;
            result.push(dayOfWeek);
        }
    });
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search