简体   繁体   中英

Closest alphabetical match in jquery/javascript

I have an array of company names, eg:

Apple
IBM
Microsoft
Xerox

I also have a string, and I want to find the closest entry in the list, alphabetically, after the place the string would be (it isn't necessarily in the list, although it might be), or the last entry in the list if the string is alphabetically greater than the last entry.

'AAA' would return 'Apple'
'IBM' would return 'IBM'
'Intel' would return 'Microsoft'
'ZZZ' would return 'Xerox'

Thanks for any suggestions!

this seems to work, item has to be larger than previous item/undefined and less than or equal to current item, otherwise last item in the sorted array

var arr = ['Apple', 'IBM', 'Microsoft', 'Xerox'].sort();
var match = (str) => arr.find((item, index) => {
    return (
        str.toLowerCase() > (arr[index - 1] || '').toLowerCase() &&
        str.toLowerCase() <= item.toLowerCase()
    );
}) || arr[arr.length - 1];

console.log(match('AAA')); // "Apple"
console.log(match('IBM')); // "IBM"
console.log(match('Intel')); // "Microsoft"
console.log(match('ZZZ')); // "Xerox"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM