Skip to content

Instantly share code, notes, and snippets.

@syntax-punk
Created October 26, 2023 13:34
Show Gist options
  • Save syntax-punk/a9679225f5caa5861917d2960028eaed to your computer and use it in GitHub Desktop.
Save syntax-punk/a9679225f5caa5861917d2960028eaed to your computer and use it in GitHub Desktop.
An Input match position priority
const cityNames = [
"Dystopya",
"Crispy Corners",
"Pyongyang",
"Pylontropolis",
"Pyramida",
"Happytown",
"Sleepy Hollow",
"Pylonville",
"Empyreal Heights"
];
function getCitySuggestions(input) {
// Filter city names based on the input
let matches = cityNames
.filter(city => city.toLowerCase().includes(input.toLowerCase()));
// Sort the matches: prioritize based on the position of the match,
// and then alphabetically
matches.sort((a, b) => {
const indexA = a.toLowerCase().indexOf(input.toLowerCase());
const indexB = b.toLowerCase().indexOf(input.toLowerCase());
if (indexA < indexB) return -1;
if (indexA > indexB) return 1;
// If the match position is the same, sort alphabetically
return a.localeCompare(b);
});
return matches;
}
// getCitySuggestions("py")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment