Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jquery/javascript中最接近的字母匹配_Javascript_Jquery - Fatal编程技术网

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

jquery/javascript中最接近的字母匹配,javascript,jquery,Javascript,Jquery,我有一系列公司名称,例如: Apple IBM Microsoft Xerox 苹果 国际商用机器公司 微软 复印机 我还有一个字符串,我想在列表中找到最接近的条目,按字母顺序,在字符串的位置之后(它不一定在列表中,尽管它可能在列表中),或者如果字符串的字母顺序大于最后一个条目,则查找列表中最后一个条目 'AAA' would return 'Apple' 'IBM' would return 'IBM' 'Intel' would return 'Microsoft' 'ZZZ' would

我有一系列公司名称,例如:

Apple IBM Microsoft Xerox 苹果 国际商用机器公司 微软 复印机 我还有一个字符串,我想在列表中找到最接近的条目,按字母顺序,在字符串的位置之后(它不一定在列表中,尽管它可能在列表中),或者如果字符串的字母顺序大于最后一个条目,则查找列表中最后一个条目

'AAA' would return 'Apple' 'IBM' would return 'IBM' 'Intel' would return 'Microsoft' 'ZZZ' would return 'Xerox' “AAA”将返回“Apple” “IBM”将返回“IBM” “英特尔”将返回“微软” “ZZZ”将返回“Xerox”
谢谢你的建议

这似乎有效,项必须大于上一项/未定义项且小于或等于当前项,否则为排序数组中的最后一项

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"
var arr=['Apple','IBM','Microsoft','Xerox'].sort();
变量匹配=(str)=>arr.find((项目,索引)=>{
返回(
str.toLowerCase()>(arr[index-1]| |“”).toLowerCase()&&

str.toLowerCase()您还需要发布您尝试过的内容。循环和比较。基本上是任何排序算法的工作原理。如果列表已排序,请查找二进制搜索