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

126
Visualizações
Proper way of creating an array or pushing into it if it already exists

In my code I have an element, and I want to have it in an array: either the array already exists and then I push my element, or it doesn't and in that case I create the array with this only element:

if (arr) {
  arr.push(elt);
} else {
  arr = [elt];
}

I'm sure there is a better way to do this. I looked into spreading and nullish coalescing operator, but I didn't find any correct syntax. Does anybody have an idea on how I could write my lines with a nicer syntax? Thanks in advance.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use the expression arr || [] to return an array which is either arr if arr is defined already or [] otherwise. Then you can simply concat the new value to it:

arr = (arr || []).concat([elt])

Note the new value needs to be enclosed in [] to prevent elt values which are arrays from being flattened.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can check if an array exists by testing if it is false-y. Thus, you can create an array if it doesn't already exist with

arr = (arr || []);

From there you can just push your new element:

arr = (arr || []);
arr.push(elt);
about 4 years ago · Juan Pablo Isaza Relatório

0

See the below code:

if (arr && arr.length > 0) {
  arr.push(elt);
  //or can use spread operator
  arr = [...arr, elt];//this should work if I am not wrong
} else {
  arr = [elt];
}

It is somewhat similar but I guess it should work fine and is a general pattern.

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