Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
Push item onto array on condition in one line

I want something like this and I would like to know if this is possible in JavaScript in one line, or I have to write an if statement

// these versions adds fasle to the array if condition = false
let arr = await getArray(params).push(condition && itemToAdd);
arr = await getArray(params).push((() => condition && itemToAdd)());

// this version adds undefined to the array if condition = false
arr = await getArray(params).push((() => { if (condition) return itemToAdd })());

(the reason I included the getArray part is cuz that's how it looks in my code and I don't actually save this array to a var arr only its being returned right away to its calling function, so that's why I don't want to add a line for the if statement...)

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Not sure why you want to do it in a single line, but this can work

let arr = [...await getArray(), itemToAdd].slice(0, condition ? undefined : -1);

Here we are pushing the itemToAdd in the array regardless of the condition, but we remove the last element (itemToAdd) if the condition is false.

about 4 years ago · Santiago Trujillo Relatório

0

if you are working with reactjs then you can use useState for conditions

const [isCondition, setisCondition] = useState(false);

//but you need if/else to change useState

if(this_happens) {

setisCondition(true) } else { setisCondition(false) }

//you can do it as like

let arr = await getArray(params).push(isCondition && itemToAdd);
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda