Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

362
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!