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

365
Visualizações
How to filter a JS array based on user input in such a way that user writes "Brl", and it shows Berlin (letters aren't one after another immediately)?

I have an array of cities var cities = ['Berlin', 'Bucharest', 'Paris', 'Munich', 'Amsterdam', 'Milan']; This array needs to be filtered based on the search input passed (f.e., user inputs 'm', and it shows 'Munich', 'Amsterdam', and 'Milan', then the user adds 'a' to 'm' in search input (writes 'ma'), and it shows him "Amsterdam' and 'Milan', although these letters are not one immediately after another). Moreover, I then need these letters to be highlighted in some way, so, let's say, letters 'm' & 'a' in these words are yellow.

This is what I've done so far, but it doesn't work as I need.

var input = document.querySelector("input").value.toLowerCase().trim();
document.addEventListener('input', search)

function search() {
 var filteredArray = cities.filter(x => x.toLowerCase().includes(input));
 console.log(filteredArray);//to see what I've got
}

Appreciate any help! I'm new to JavaScript. Thanks!

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

0

You might filter like this.

document.addEventListener('input', search);

const cities = ['Berlin', 'Bucharest', 'Paris', 'Munich', 'Amsterdam', 'Milan'];

function search(e) {
  const input = e.target.value.toLowerCase().trim();
  const filteredArray = cities.filter(x => {
    const c = x.toLowerCase();
    let m = 0;
    for (let l of input) {
      const i = c.substr(m).indexOf(l);
      if (i < m) return false;
      m = i;
    }
    return true;
 });
 console.log(filteredArray);//to see what I've got
}
<input>

Also, you might remember indexes to highlight matching letters.

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