Home > OS >  How do I use filter inside filter in react
How do I use filter inside filter in react

Time:03-03

I have an array getting from an API data, I would like to filter categories if it's in category. I was trying like :

data.filter((post) => post.categories.filter((category) => if(category._id === category) return category

It didn't work for me

Here is my array data :

export interface Post {
  categories: Category[]
  publishedAt: string
  _id: string
  _createdAt: string
  title: string
  author: {
    name: string
    image: string
  }
  comments: Comment[]
  description: string
  mainImage: {
    asset: {
      url: string
    }
  }
  slug: {
    current: string
  }
  body: [object]
}

export interface Category {
  _id: string
  _ref?: string
  title: string
}

and I tried this too

posts.map((post) => {
  post.categories.filter((category) => {
    if (category._ref === isCategory) return category;
  });
  {
    return <Posts post={post} />;
  }
});

How can I do it ?

CodePudding user response:

You need at first get the list of post that have in the array category the dedicated category. Try this solution

const postsWithCategory = posts.filter((post) => post.categories.findIndex(cat => cat._ref === isCategory) !== -1);
postsWithCategory.map(post => (<Posts post={post} />));

CodePudding user response:

I guess you want to get the posts having a specific category. You can filter the posts based on if some of the categories are equal to the defined category id.

Try like this.

{data
  .filter((post) => post.categories.some((cat) => cat._id === category))
  .map((post) => (
    <Posts post={post} />
  ))}
  • Related