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

84
Visualizações
Return undefined on empty nested arrays with flat

I'm using flat() to count the number of empty or undefined items inside a nested array.

[[undefined, 4], [4]]

Using flat on this array will return 3 items:

  1. undefined
  2. 4
  3. 4

However on this array:

[[], [], []]

using flat will return an empty array.

Is there a way to use it so it returns 3 undefined items?

almost 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You have to use flatMap for this reason:

[[], [], []].flatMap(item => item.length ? item : undefined)

returns what you need

almost 4 years ago · Santiago Trujillo Relatório

0

arr=[[],[],[]]

console.log(arr.reduce((acc, val) => acc.concat(val==''?undefined:val),[]));

according to js MDN docs combination of reducer and concat simmilar to the exact Array.prototype.flat function. therefor altering it you can get your expected answer.the code for that is as above.

almost 4 years ago · Santiago Trujillo Relatório

0

If your array is n-level nested then you can create recursive function to achieve the desired result:

const flat = arr => arr.flatMap(o=> o?.length ? flat(o) : Array.isArray(o) ? undefined : o );

console.log(flat([[], [], []]));
console.log(flat([[undefined, 4], [4]]));
console.log(flat([[undefined, [[],[],[]], 4], [4,[]]]));

almost 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