Home > Net >  js array filter based on two boolean conditions
js array filter based on two boolean conditions

Time:04-06

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

CodePudding user response:

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 
  }
);

CodePudding user response:

try,

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