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

Smarter way of using filter and map instead of filter and loop

I want to create a smarter way of coding of the following example. Important is that each loop (for activeFilters) needs to be fully done, before we want to return the filtersTest.

const createFilters = async () => {
 const filtersTest = [] as any

 // Only create active filters by checking count.
 const activeFilters = getComponentFilter.value.filter(function(item) {
  if (item.items) {
    return item.items.some((obj) => obj.count)
  }
 });

 // Loop through the active filters and push arrays into the object.
 for(let i = 0 ; i < activeFilters.length; i++) {

  const options = await createFilterOptions(activeFilters[i].id, activeFilters[i].items);

  const array = {
    defaultValue: null,
    id: activeFilters[i].id,
    value: 'nee',
    label: activeFilters[i].label,
    options: options,
  }
  
  filtersTest.push(array)
 }

 return filtersTest;
}

>Solution :

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

First of all, it should be clear that createFilters is not going to return the array, but a promise that will eventually resolve to that array.

With that in mind, you can reduce your code a bit, using Promise.all, the ?. operator, destructuring parameters, and shorthand property names in object literals:

const createFilters = () => Promise.all(
    getComponentFilter.value.filter(({items}) =>
        items?.some((obj) => obj.count)
    ).map(({id, label, items}) => 
        createFilterOptions(id, items).then(options => ({
            defaultValue: null,
            id,
            value: 'nee',
            label,
            options
        }))
    )
);
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