Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove redundant if object javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does anyone have another solution for me to explore?

>Solution :

  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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading