javascript 搜索数组返回部分匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5440275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:12:17  来源:igfitidea点击:

Search an array return partial matches

javascriptarrayssearchmootools

提问by Mike L.

I need to search an associative array's values for a string, but only the beginning of the string example:

我需要搜索字符串的关联数组的值,但只搜索字符串示例的开头:

var stack = ['aba', 'abcd', 'ab', 'da', 'da'];

a search on stack for the value awould return ['abc, 'abcd', 'ab'], and for bwould just return b while a search for 'd' would return [da', 'da']...any way to do that?

在堆栈上搜索该值a将返回['abc, 'abcd', 'ab'],而 forb将仅返回 b 而搜索 'd' 将返回[da', 'da']......有什么方法可以做到这一点?

Im trying to do like an autocomplete select box, but its custom so i need to moditor text events and search my array of items to get the index of the first match while the user is typing.

我试图做一个自动完成选择框,但它是自定义的,所以我需要修改文本事件并搜索我的项目数组以在用户键入时获取第一个匹配项的索引。

回答by Dimitar Christoff

upvoted @Mrbuubuu but you can do this as a prototype and pass the filter element through the String .containsto be more mootools-ish and cater for matches in the middle, like 'cd' which should return results.

upvoted @Mrbuubuu 但您可以将其作为原型来执行,并将过滤器元素通过 String.contains传递,使其更像 mootools 并迎合中间的匹配项,例如应该返回结果的 'cd'。

eg case, an array of brands, one of which is the north faceand a user searching for northshould return the matched brand but it won't as they missed the

例如,一系列品牌,其中一个是the north face,用户搜索north应该返回匹配的品牌,但不会因为他们错过了the

additionally, you need to make sure the case is lowered on the search string and the stack array elements when you compare values.

此外,当您比较值时,您需要确保搜索字符串和堆栈数组元素的大小写降低。

here's an example with an input that works: http://jsfiddle.net/dimitar/M2Tep/

这是一个输入有效的示例:http: //jsfiddle.net/dimitar/M2Tep/

(function() {
    Array.implement({
        subStr: function(what) {
            return this.filter(function(el) {
                return el.charAt(0) == what;
                // return el.contains(what); // any position match
            });
        }
    });
})();

// return the original array elements
console.log(['aba', 'abcd', 'ab', 'da', 'da'].subStr("d")); 
// ["da", "da"]

alternatively, you mentioned in a comment that all you really wanted to get were just the indexes in your original array:

或者,您在评论中提到您真正想要的只是原始数组中的索引:

(function() {
    Array.implement({
        getIndexes: function(what) {
            var indexes = [];
            this.each(function(el, index) {
                if (el.charAt(0) == what)
                    indexes.push(index);
            });
            return indexes;
        }
    });
})();


console.log(['aba', 'abcd', 'ab', 'da', 'da'].getIndexes("d")); 
// [3,4]

although since this does not return the array, it would break chaining hence it should not be a prototype of array but just a function.

虽然因为这不返回数组,它会破坏链接,因此它不应该是数组的原型而只是一个函数。

回答by moe

/**
 * Extend the Array object
 * @param candid The string to search for
 * @returns Returns the index of the first match or -1 if not found
*/
Array.prototype.searchFor = function(candid) {
    for (var i=0; i<this.length; i++)
        if (this[i].indexOf(candid) == 0)
            return i;
    return -1;
};

Then you can use it like :

然后你可以像这样使用它:

var index = stack.searchFor('a');

回答by JWC

If you want to use mootools to do this, you can use the filter method from mootools:

如果你想使用 mootools 来做到这一点,你可以使用 mootools 中的 filter 方法:

function search(arr, letter) { 
    var matches = arr.filter(function(str) {
        return str.charAt(0) == letter;
    });

    return (matches.length > 0) ? matches : letter;
}

search(stack, 'd'); //returns ['da', 'da']

回答by Karthik

The simplest vanilla javascript to achieve this is

实现这一目标的最简单的香草 javascript 是

var stack = ['aba', 'abcd', 'ab', 'da', 'da', undefined, , false, null, 0];
var prefixTextToFind = "a"; //b, c or d

var matches = stack.filter(function(stackValue){
  //get rid of all falsely objects
  if(stackValue) {
    return (stackValue.substring(0, prefixTextToFind.length) === prefixTextToFind);
  }
}); //["aba", "abcd", "ab"]

回答by wong2

Array.prototype.startWith = function(c){
    var result = [];
    for(var i=0, len=this.length; i<len; i++){
        if(this[i].indexOf(c) == 0){
            result.push(this[i]);
        }
    }
    return result || c;
};