TarekRaafat / autoComplete.js

Simple autocomplete pure vanilla Javascript library.
https://tarekraafat.github.io/autoComplete.js
Apache License 2.0
3.95k stars 240 forks source link

Sorting post code results based on first number. #203

Closed AllenXavier closed 3 years ago

AllenXavier commented 3 years ago

Hi,

I am using your autocomplete library to autocomplete postal codes. This is working so far, however. I would like it to show the results based on the first matching number.

Right now if I type in a 9, i get the first results containing a 9 not the results starting with a 9.

It is giving me this:

Screenshot 2021-04-14 at 16 38 14

Instead of the 9000 numbers first:

Screenshot 2021-04-14 at 16 38 19

Is this a possibility with your library?

regards,

TarekRaafat commented 3 years ago

Hello @AllenXavier,

Yes, you can achieve that using the data.results API to sort the results according to your own criteria before rendering the list as shown below.

results: (list) => {
  const value = document.querySelector("#autoComplete").value.slice(0, 1);
    // Sort results by starting character
    const sortedList = list.sort((a, b) => {
      if (!a.match.startsWith(value)) return -1;
      if (a.match.startsWith(value)) return 1;
      return 0;
    });
  // Return sorted list
  return sortedList;
}
Screen Shot 2021-04-15 at 8 56 11 AM

Try it and let me know how it goes.

Have a nice day! :)

jsunsawyer commented 3 years ago

@TarekRaafat Thanks for this. Though there is an error with your results code. We got this working by reversing your return values for the startsWith checks.

Here's an updated version with the addition of making results case insensitive. Note that threshold is a variable (3 in our case) that matches our threshold setting.

results: (list) => {
  const value = (this.fieldTarget.value.slice(0, threshold)).toLowerCase();
  // Sort results by starting character
  const sortedList = list.sort((a, b) => {
    const listItemValue = a.value.title.toLowerCase();
    if (!listItemValue.startsWith(value)) return 1;
    if (listItemValue.startsWith(value)) return -1;
    return 0;
  });
  // Return sorted list
  return sortedList;
}
TarekRaafat commented 3 years ago

Hello @jsunsawyer,

Thanks for the correction much appreciated.

Cheers, and have a nice day! :)