Created
October 26, 2023 13:34
-
-
Save syntax-punk/a9679225f5caa5861917d2960028eaed to your computer and use it in GitHub Desktop.
An Input match position priority
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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