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

146
Views
Javascript: Conditionally add objects to array in one line

In my JS code I have two booleans, flag1 and flag2. I want to create an array ['a', 'b', 'c'] where a is included only if flag1 is true, and where b is included only if flag2 is true. What I have now is [flag1 ? 'a' : null, 'b', flag2 ? 'c' : null], but if flag1 and flag2 are false this gives me [null, 'b', null] instead of ['b'].

SOLUTION:

Here's the cleanest way I found for doing it: [...(flag1 ? ['a'] : []),'b',...(flag2 ? ['c'] : [])]

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

0

You could take a function which returns either the value inside an array or an empty array for spreading into an array.

const
    either = (condition, value) => condition ? [value] : [],
    getArray = (flag1, flag2) => [
        ...either(flag1, 'a'),
        ...either(flag2, 'b'),
        'c'
    ];
    
console.log(...getArray(true, true));
console.log(...getArray(false, true));
console.log(...getArray(true, false));
console.log(...getArray(false, false));

about 4 years ago · Juan Pablo Isaza Report

0

Another one implementation:

const flag1 = true;
const flag2 = false;
const data = [[flag1, 'a'], [flag2, 'b'], [true, 'c']];

const result = data.flatMap(([flag, letter]) => flag ? letter : []);

console.log(result);

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!