Search code examples
javascriptarrayssearchmootools

Search an array return partial matches


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.


Solution

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