0

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

2
  • 1
    if (condition1 && condition2) Commented May 4, 2020 at 6:13
  • return true only if all condition are satisfied Commented May 4, 2020 at 6:13

2 Answers 2

1

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

        }
Sign up to request clarification or add additional context in comments.

Comments

1

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'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.