0

I have two boolean conditions to filter an array. An array will always have 3 items within, and first condition always removes 2nd item, second condition 3rd one. And I successfully filtering it using .filter. But seems my approach a bit dirty, is there any better, clear way to filter?

  const firstCondition = true;
  const secondCondition = true;

  const arrayToFilter: Array<string> = ['firstItem', 'secondItem', 'thirdItem'].filter(
    (item, idx) =>
      firstCondition && secondCondition 
        ? item
        : !firstCondition && secondCondition 
        ? idx !== 1
        : !firstCondition && !secondCondition 
        ? idx === 0
        : firstCondition && !secondCondition && idx !== 2
  );

console.log(arrayToFilter);

Edit: Clarification If Conditions are false they removes items

2 Answers 2

1

How about this?

 const arrayToFilter: Array<string> = ['firstItem', 'secondItem', 'thirdItem'].filter(
(item, idx) => {
    if (!firstCondition && idx === 1) return false
    if (!secondCondition && idx === 2) return false
    else return true 
  }
);
Sign up to request clarification or add additional context in comments.

2 Comments

Nice, but I've changed logic a bit to fulfill my expectations, to !firstCondition, !secondCondition. Definitely better than what I wrote.
Oh, I see what you mean now. I have updated my answer to fit your edited description.
0

try,

....
(item, index) => (
  (firstCondition && index !== 1)
  || (secondCondition && index !== 2)
  || true // (!firstCondition && !secondCondition)
)

3 Comments

Your approach is looking pretty, but seems your first two conditions within brackets() has to return false to properly filtering but they returning true, or I am missing something? I've tried to use it but it gives me wrong result. Like if 1-true, 2-true I see an empty array.
yeah, index values were wrong 2 & 3, instead of 1 & 2
No, I've changed them to 1&2 before checking)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.