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

Javascript : skip calling the chaining methods based on a condtion dynamically

I have an array of objects, I call a series of methods on the array. I wanted to skip in between methods based on a condition. Is there a generic way to handle it instead of having an if/else block?

When a filter is applied i wanted to call filter method in this array, when filter is not applied i want skip that.

// when filter is applied
    salesActivityTypes
         .filter(s=>s.selected)
         .map(key => key.name);

//when filter not applied
    salesActivityTypes
         .map(key => key.name);

I don’t want to use something like if/else block and copy-pasting the same code twice. Is there any better way to handle this?

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

The order of methods call matters and should’nt change

>Solution :

Just add another check inside the .filter callback for whether filtering is active.

salesActivityTypes
     .filter(s => filteringActive ? s.selected : true)
     .map(key => key.name);
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