Search code examples
javascriptreactjsecmascript-5

Combine two filter rules for an array of objects


I'm using React Redux and I have an array of objects which I'm displaying in a list. I'm having an option to filter the list via a dropdown, depending on a name, and by two toggle buttons, based on kind.

<Table
  data={
    array
      .filter((a) => a.kind === showByKind)
      .filter((a) => a.name === filterValue)
      .sort(someIrrelevantSortMethod)
  }
>

Question is how do I combine the two .filter() rules?


Solution

  • Combining two filters means you need both to apply. In other words, you need (condition 1) AND (condition 2).

    So basically:

    <Table
      data={
        array
          .filter((a) => a.kind === showByKind && a.name === filterValue)
          .sort(someIrrelevantSortMethod)
      }
    >