Skip to content
Advertisement

How do I use filter inside filter in react

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 ?

Advertisement

Answer

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} />));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement