Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
js array filter based on two boolean conditions

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 
  }
);
about 4 years ago · Juan Pablo Isaza Report

0

try,

....
(item, index) => (
  (firstCondition && index !== 1)
  || (secondCondition && index !== 2)
  || true // (!firstCondition && !secondCondition)
)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!