搜索数组返回部分匹配 [英] Search an array return partial matches

查看:91
本文介绍了搜索数组返回部分匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在关联数组的值中搜索一个字符串,但仅搜索字符串示例的开头:

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 将返回 ['abc,'abcd','ab'] ,对于 b 仅返回b,而a搜索'd'将返回 [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.

推荐答案

赞成@Mrbuubuu,但您可以将其作为原型,并通过字符串 .contains 变得更像工具,并迎合中间的匹配,例如 cd应返回结果。

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.

例如,案例,一系列品牌,其中一个是北脸,并且搜索的用户应返回匹配的品牌,但不会丢失匹配的品牌 the

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.

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

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.

这篇关于搜索数组返回部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆