簡體   English   中英

搜索數組返回部分匹配

[英]Search an array return partial matches

我需要搜索字符串的關聯數組的值,但只搜索字符串示例的開頭:

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

一個堆棧搜索的值a將返回['abc, 'abcd', 'ab'] ,和b只想返回b而對於搜索‘d’將返回[da', 'da'] ...有什么辦法做到這一點?

我試圖做一個自動完成選擇框,但它是自定義的,所以我需要修改文本事件並搜索我的項目數組以在用戶鍵入時獲取第一個匹配項的索引。

贊成@Mrbuubuu,但您可以將其作為原型來執行,並將過濾器元素通過 String .contains給更多的 mootools-ish 並迎合中間的匹配項,例如應該返回結果的 'cd'。

例如,一系列品牌,其中一個是the north face ,搜索north的用戶應該返回匹配的品牌,但不會因為他們錯過the

此外,您需要確保在比較值時搜索字符串和堆棧數組元素的大小寫降低。

這是一個輸入有效的示例: 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"]

或者,您在評論中提到您真正想要的只是原始數組中的索引:

(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]

雖然因為這不返回數組,它會破壞鏈接,因此它不應該是數組的原型而只是一個函數。

/**
 * 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;
};

然后你可以像這樣使用它:

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

實現這一目標的最簡單的香草 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"]

如果你想使用 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']
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;
};

更好的方法是使用array.includes 它更易於使用,您可以獲得更快的結果......

例子:

let search = 'test'
let list = ['te', 'test', 'sample', 'john']
list.includes(search.toLowerCase()) // returns the `te` and `test`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM