Klick
Klick

Reputation: 1653

Js filter on condition if exist

I would like to filter array on some condition using "filter" method. If only one condition is active there is no problem. But if object in array must be under two condition there is a problem.

getFilteredItems() {
      let customText = this.filters.customTextFilter.trim();
      return this.filteredItems.filter((x) => {

        if (customText !== '') {
          return x.name.includes(customText) || x.code.includes(customText) || x.city.includes(customText);
        }

        if (this.filters.currencySelected !== '') {
          return x.currency === this.filters.currencySelected;
        }
        return true;
      })
    }

How to join both condition if both are selected? I have another 3 conditions to join. So if some one select two condition how to check both in object and return true if both are true?

Thank you

Upvotes: 0

Views: 1963

Answers (2)

Muhammed B. Aydemir
Muhammed B. Aydemir

Reputation: 1015

You could create an array, which holds your filters, and use the reduce function to iterate over it:

const filteredItems = [
    {
        name: 'USA',
        city: 'Washington',
        code: '',
        currency: '$'
    },
    {
        name: 'Germany',
        city: 'Berlin',
        code: '',
        currency: '€'
    },
    {
        name: 'Turkey',
        city: 'Istanbul',
        code: '',
        currency: '₺'
    }
]

const getFilteredItems = (customText = '', currencySelected = '') => {
    const myFilters = []
    if (customText !== '') {
        myFilters.push(x => x.name.includes(customText) || x.code.includes(customText) || x.city.includes(customText));
    }
    if (currencySelected !== '') {
        myFilters.push(x => x.currency === currencySelected);
    }
    return filteredItems.filter(x => myFilters.reduce((acc, myFilter) => acc && myFilter(x), true))
}

console.log(getFilteredItems('Istan'))

Upvotes: 1

upog
upog

Reputation: 5531

Have a result variable and set to false when ever condition is not satisfied and return the result

getFilteredItems() {

          let customText = this.filters.customTextFilter.trim();
          return this.filteredItems.filter((x) => {
            result=true;
            if (customText !== '') {
              result = result &&( x.name.includes(customText) || x.code.includes(customText) || x.city.includes(customText));
            }

            if (this.filters.currencySelected !== '') {
              result = result &&( x.currency === this.filters.currencySelected);
            }
            return result;
          })

        }

Upvotes: 1

Related Questions