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

228
Visualizações
Return no element from `Array.flatMap()` by if condition

I have this code:


  const myFunc = function (t) {
    return myArray.flatMap(clip =>
      (t < clip.start || t < clip.end) ? // Valid objects are returned in this *if* condition
        [
          { time: clip.start },
          { time: clip.end }
        ] : // how to return nothing in this *else* condition. Absolutely nothing?
        [
          {  },
          {  }
        ]
    )
  }

The above code used a ternary operator of condition ? exprIfTrue : exprIfFalse.

Currently I'm returning empty objects of { } in the case of exprIfFalse.

How can I return nothing in the case of exprIfFalse? I mean, I want absolutely nothing. I mean no array element.

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

0

Why cant you just return an empty array, any how Array.flat will remove those empty array from final code. In your case the array is not empty as [], its an array with two empyty objects as [{}, {}] that will produce two empty objects {}, {} in the final output after Array.flat

You have to return something from flatMap. If you return nothing, the corresponding nodes will be added as undefined. That wont be removed with Array.flat. Best option is to return an empty array as below.

Pseudo Code

const myArray = [1, 2, 3, 4, 5];
const myFunc = function (t) {
  return myArray.flatMap(clip =>
    (clip % 2 === 0) ? // Valid objects are returned in this *if* condition
      [
        { value: clip },
        { value: clip }
      ] : // how to return nothing in this *else* condition. Absolutely nothing?
      []
  )
}
console.log(myFunc());

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