Home > Software engineering >  Javascript: Conditionally add objects to array in one line
Javascript: Conditionally add objects to array in one line

Time:03-11

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'] : [])]

CodePudding user response:

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

CodePudding user response:

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

  • Related