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

247
Visualizações
How to tell if the list is empty using "filter" and "map"
      list
        .filter((val) => {
          if (
            val.name.toLocaleLowerCase().includes(input))
          ) {
            return val
          }
        })
        .map((val, idx) => (
          <Li
            key={idx}
          />
        ))

Using this structure, I wanted to do something if returns empty.

Ex: When searching for "abc" and there is no "abc" in the list, a message appears saying that "abc" was not found.

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

0

Several things to change:

1. Your filter expression is only working by accident

list
    .filter((val) => {
      if (
        val.name.toLocaleLowerCase().includes(input))
      ) {
        return val
      }
    })

can be just

list
    .filter(val => val.name.toLocaleLowerCase().includes(input)

Remember that the function inside filter just returns a true or false. By chance your expression, which returns the actual list element, is interpreted as true, and when your expression does not match, you don't return anything, which has the same effect as returning false. Expressing it as above makes it clearer what you are doing (and is very marginally faster).

2. To get your error message, save the output of the filter so you can test its length.

const matches = list.filter(val => val.name.toLocaleLowerCase().includes(input)

const output =  (matches.length>0) ? 
    matches.map((val, idx) => (
      <Li
        key={idx}
      />
    )) : (
      <div>Not found</div>
    )
about 4 years ago · Juan Pablo Isaza Relatório

0

You can tell if the list is empty using "filter" and "map" by using following JavaScript Code:

list
.filter((value) => (value!==undefined) && (value!==null) && value.name.toLocaleLowerCase().includes(input)))
.map((value, id) => (
          <Li
            key={id}
          />
))
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