Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda