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

134
Visualizações
Simplify the design for auto-suggestion

There is a rather complicated construction in my code, it is in const matchedSuggestions. This construction is responsible for auto-suggestions. For example: there are several male names (Adam, Adrian, Arnold, Mike). The user enters the first letter "A" and sees auto-suggestions - Adam, Adrian, Arnold. Then he enters the letter "D" and remains in auto-suggestions - Adam, Adrian. And so on.

Is it possible to somehow simplify this part of the code?

const onChange = (e) => {
  const { value } = e.target;
  setInput(value)

  if(value.length < 1) { setSuggestedTags([]); setIsValid([]);return; }
  
  const matchedSuggestions = tagSuggestions.filter((s) => {
    return s.slice(0, 2).search(value.slice(0, 2)) > -1 
        && s.slice(0, 1).search(value.slice(0, 1)) > -1
        && s.slice(0, 3).search(value.slice(0, 3)) > -1
        && !tags.includes(s)
  })
  setSuggestedTags(matchedSuggestions); 

  if (e.target.value) {
    setIsValid(() => /^[1-5][0-9]?[0-9]?$|^100$/.test(e.target.value));
  } else {
    setIsValid(true);
  }
  setInput(value);
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could get the length of the input string and use it as index for slicing. Even better, you could use startsWith and if wanted normalized to upper or lower case, like

 value = value.toLowerCase();             // normalize
 tagSuggestions.filter(s =>
     s.toLowerCase().startsWith(value) && // or includes(value) in case you want to validate part of the string
     !tags.includes(s)                    // what is this for?
 );
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