bk___
bk___

Reputation: 71

How to conditionally include a filter in javascript array

I have a component where I am mapping through an array of items. I am adding a filter to it as well. Right now it looks like this:

{data.products                  
  .filter((item) => item.acf.quiz.gender.some(({ value }) => value === state.theme.quiz.quizGender))
  .map((item, id) => {
    return <ProductCard key={id} item={item} data={data} />;
  })
}

So if the gender has been set to state by a radio button in another component, the map will filter by items where that gender is an attribute. I have that part working just fine.

What I am trying to figure out though, is if there is a way to conditionally apply that filter, so that if the use didn't set their gender, then the filter would not apply. I know there is a way to do this outside of the map, but I am needing to do it inline with this .filter() as there will be several more filters that I will need to apply.

Any help would be great.

Upvotes: 0

Views: 442

Answers (3)

Obzi
Obzi

Reputation: 2390

You just need to return true on the filter if state isn't set :

{
    data.products
        .filter((item) => 
            !state?.theme?.quiz?.quizGender
            || item.acf.quiz.gender.some(({
                    value
                }) => value === state.theme.quiz.quizGender)
        )
        .map((item, id) => {
            return <ProductCard key = {id} item={item} data={data} />;
        })
}

Upvotes: 0

epascarello
epascarello

Reputation: 207557

So as long as the non selection state is null/undefined/false you can just add a check inside the filter

.filter((item) => 
  !state.theme.quiz.quizGender || 
  item.acf.quiz.gender.some(({ value }) => 
    value === state.theme.quiz.quizGender)
)

Upvotes: 1

Ketan Ramteke
Ketan Ramteke

Reputation: 10685

You can apply a check to see if item.acf.quiz.gender has a value, if yes then continue with the operation else, return false

{
  data.products
    .filter((item) =>
      item.acf.quiz.gender
        ? item.acf.quiz.gender.some(
            ({ value }) => value === state.theme.quiz.quizGender
          )
        : false
    )
    .map((item, id) => {
      return <ProductCard key={id} item={item} data={data} />;
    });
}

Upvotes: 0

Related Questions