Search an array return partial matches

[亡魂溺海] 提交于 2020-07-23 05:09:05

问题


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 a would return ['abc, 'abcd', 'ab'], and for b would just return b while a search for 'd' would return [da', 'da'] ...any way to do that?

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.


回答1:


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

eg case, an array of brands, one of which is the north face and a user searching for north should return the matched brand but it won't as they missed 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/

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




回答2:


/**
 * 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');



回答3:


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

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



回答4:


The simplest vanilla javascript to achieve this is

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



回答5:


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


来源:https://stackoverflow.com/questions/5440275/search-an-array-return-partial-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!