I've been struggling with the same piece of code for a few days by now...

So for the html part I have this : 

```html
<input type="text" id="search_immobilier_ville" name="search_immobilier[ville]">
<div class="collection" id="search-ville-collection"></div>

```

I have an input where I have to type any city name, then I want to filter the matching cities names into an existing array of cities like this : 

```none
let api_results = [['Le Moule',97152],['Lamentin',97189],...]
let ville_input = document.getElementById('search_immobilier_ville');

```

Then display the matching cities as a list of elements in the div `#search-ville-collection`.

On each keyup event, I need to perform this action, and update the visual list in real time.

My issue is that my filtering system is messed up, if I search "lam" for example, I can get a city called "**lam**entin" (pass the test) and another with just the "la" matching like "capesterre-de-marie-ga**la**nte"

So far, I've done this : 

```js
// Previously filled by an API
let api_results = [[name,postalCode],[name,postalCode],...];

ville_input.addEventListener('keyup', () => {
  let value = ville_input.value.toUpperCase().trim();

  // User input
  let input_val = ville_input.value.toUpperCase().trim();

  // Filtering through var ville_input
  api_results.forEach(el => {
    if (el[0].toUpperCase().startsWith(input_val) || input_val.length >= 2 && el[0].toUpperCase().includes(input_val)) {
      result_list.style.display = 'block';

      // if city not present in the html list, add it
      if (document.getElementById(el[1]) === null) {
        $(result_list).append(`<a class="collection-item search-ville-results" id="${el[1]}"> ${el[0]} - ${el[1]} </a>`);
      }
    }
  }); // End forEach

  /* Looping through the collection child nodes to check
    if there are cities that don't match the user input */
  for (let child of result_list.children) {
    console.log(child)

    // if the user input doesn't match with an existing city in the node, delete the node
    if (!child.text.toUpperCase().includes(input_val)) {
      result_list.removeChild(child);
    }
  }

  // Highlight first element of the list
  result_list.firstElementChild.classList.add('active');

  // empty results div if user input is empty
  if (input_val == '') {
    result_list.style.display = 'none';
    result_list.innerHTML = '';
  }
});

```

This code works PARTIALLY. For example, if I type "lam", I'm supposed to get only one result based on my result set, but check out this scenario : 

### Typing "l":

![Screenshot "l"](https://i.stack.imgur.com/fguKn.png)

### Typing "la":

![Screenshot "la"](https://i.stack.imgur.com/1spVV.png)

### Typing "lam":

![Screenshot "lam"](https://i.stack.imgur.com/sAiza.png) 

(Here you begin to see the issue)

### Typing "lame":

![Screenshot "lame"](https://i.stack.imgur.com/A3hF1.png)

I'm sure there's something wrong in my code, but I can't figure out what.