Home > database >  Smarter way of using filter and map instead of filter and loop
Smarter way of using filter and map instead of filter and loop

Time:03-24

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;
}

CodePudding user response:

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
        }))
    )
);
  • Related