andrecj
andrecj

Reputation: 167

Properly filter an array inside other array in reactjs

Hello I am trying react for the first time and I am having some trouble with my filter function. Here's the code:

So this is my render method in my component:

const categoryFilter = this.state.appItems.filter(item =>
      item.categories.filter(str => {
        return str.includes(active);
      })
    );

const appList = categoryFilter.map(appItem => (
      <AppItem appItem={appItem} key={appItem.id}></AppItem>
    ));

return (
      <React.Fragment>
        <div className="flex-container">
          <NavCategories
            categories={this.state.categories}
            onClick={this.handleClick}
            active={active}
          />
          <section className="apps-list">
            <header>
              <input type="text" placeholder="Search by App" />
            </header>
            <ul>{appList}</ul>
          </section>
        </div>
      </React.Fragment>
    );

this.state.appItems is an array coming from a json file, here's a snippet:

[ {
    "id": "12312",
    "name": "Test",
    "description": "test.",
    "categories": ["Voice", "Delivery", "Optimization"],
    "subscriptions": [
      {
        "name": "Trial",
        "price": 0
      },
      {
        "name": "Professional",
        "price": 3500
      }
    ]
  },]

Active is a string to manage active class items on another component.

Everything renders correctly, but it is never filtered even though the active state is changing everytime. I have tried multiple ways, but this Filter method is getting me confused a lot because I want to filter an array thats inside another array and want to filter the whole AppItem array.

If anyone could explain/give me some tips I would love it. Thanks in advance :)

Upvotes: 0

Views: 1523

Answers (1)

jered
jered

Reputation: 11571

Array.filter() returns a new array with the filtered elements in it. So your inner filter will always return an array of at least zero elements, which evaluates to a truthy value, and your outer filter will just include every element in the original array.

Just switch your inner filter to be an Array.includes() instead, which will return true or false.

const categoryFilter = this.state.appItems.filter(item =>
  item.categories.includes(active)
);

Upvotes: 1

Related Questions