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!
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.