简体   繁体   English

jquery/javascript中最接近的字母匹配

[英]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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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