javascript 如何获取字符串数组并对其进行过滤?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8839815/
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-26 04:44:48  来源:igfitidea点击:

How do I take an array of strings and filter them?

javascriptjqueryarraysfilter

提问by amlane86

I have an array of strings in jQuery. I have another array of keywords that I want to use to filter the string array.

我在 jQuery 中有一个字符串数组。我有另一个关键字数组,我想用它来过滤字符串数组。

My two arrays:

我的两个数组:

    var arr = new Array("Sally works at Taco Bell", "Tom drives a red car", "Tom is from Ohio", "Alex is from Ohio");

    var keywords = new Array("Tom", "Ohio");

How can I filter the arrarray using the keywordsarray in jQuery? In this situation it would filter out "Sally works at Taco Bell" and keep the rest.

如何arr使用keywordsjQuery 中的数组过滤数组?在这种情况下,它会过滤掉“Sally 在 Taco Bell 工作”并保留其余部分。

Below is the actual code I am using.

下面是我正在使用的实际代码。

var keywords= [];
var interval = "";
var pointer = '';
var scroll = document.getElementById("tail_print");

$("#filter_button").click(
function(){
    var id = $("#filter_box").val(); 
    if(id == "--Text--" || id == ""){
        alert("Please enter text before searching.");
    }else{
        keywords.push(id);
        $("#keywords-row").append("<td><img src=\"images/delete.png\" class=\"delete_filter\" /> " + id + "</td>");
    }
}
);

$(".delete_filter").click(
function(){
   ($(this)).remove(); 
}
);

function startTail(){
clearInterval(interval);
interval = setInterval(
function(){
    $.getJSON("ajax.php?function=tail&pointer=" + pointer + "&nocache=" + new Date(),
        function(data){
            pointer = data.pointer;
            $("#tail_print").append(data.log);
            scroll.scrollTop = scroll.scrollHeight;
        });
}, 1000);
}

The whole purpose of this is to allow the user to filter log results. So the user performs an action that starts startTail()and $.getJSON()retrieves a JSON object that is built by a PHP function and prints the results. Works flawlessly. Now I want to give the user the option to filter the incoming tailing items. The user clicks a filter button and jQuery takes the filter text and adds it to the keywordsarray then the data.logfrom the JSON object is filtered using the keywordsarray and then appended to the screen.

这样做的全部目的是允许用户过滤日志结果。因此,用户执行一个操作,启动startTail()$.getJSON()检索由 PHP 函数构建的 JSON 对象并打印结果。工作完美。现在我想让用户选择过滤传入的尾随项目。用户单击过滤器按钮,jQuery 获取过滤器文本并将其添加到keywords数组中,然后data.log使用keywords数组过滤来自 JSON 对象的内容,然后附加到屏幕上。

I also have a delete filter function that isn't working. Maybe someone can help me with that.

我还有一个不起作用的删除过滤器功能。也许有人可以帮助我。

回答by Esailija

$.grep( arr, $.proxy(/./.test, new RegExp(keywords.join("|"))));

without jQuery:

没有 jQuery:

arr.filter(/./.test.bind(new RegExp(keywords.join("|"))));

回答by georg

jQuery's word for "filter" is grep

jQuery 的“过滤器”一词是grep

var arr = ["Sally works at Taco Bell", "Tom drives a red car", "Tom is from Ohio", "Alex is from Ohio"];
var keywords = ["Tom", "Ohio"];

var regex = new RegExp(keywords.join("|"));

result = $.grep(arr, function(s) { return s.match(regex) })

回答by Chris Pratt

var filtered = [];
var re = new RegExp(keywords.join('|'));

for (var i=0; i<arr.length; i++) {
    if (re.search(arr[i])) {
        filtered.append(arr[i]);
    }
}

UPDATE

更新

Since there's better answers here from a jQuery perspective, I modified my answer to a vanilla JavaScript approach, just for those who might need to do this without jQuery.

由于从 jQuery 的角度来看这里有更好的答案,因此我将我的答案修改为 vanilla JavaScript 方法,仅适用于那些可能需要在没有 jQuery 的情况下执行此操作的人。

回答by Richard Neil Ilagan

Top of head, and untested. As a jQuery plugin:

头顶,未经测试。作为一个 jQuery 插件:

(function($) {

    $.foo = function(needle, haystack) {
        return $.grep(haystack, function () {
            var words = this.split(' '),
                flag = false
                ;

            for(var i=0; i < words.length; i++) {
                flag = $.inArray(words[i], needle);
                if (flag) { break; }
            }

            return flag;                
        });
    };

})(jQuery);

Then you can (supposedly) run that like:

然后你可以(据说)像这样运行:

var bar = $.foo(keywords, arr);

回答by Explosion Pills

var keywords = ['Tom', 'Ohio'];
var arr = ['Sally works at Taco Bell', 'Tom drives a red car', 'Tom is from Ohio', 'Alex is from Ohio'];
var matcher = new RegExp(keywords.join('|'));
var newarr = [];
$.each(arr, function(index, elem) {
   if (elem.match(matcher)) {
      newarr.push(elem);
   }
});
console.log(newarr);

fiddle: http://jsfiddle.net/LQ92u/1/

小提琴:http: //jsfiddle.net/LQ92u/1/

回答by greut

Using jQuery awesome powers:

使用 jQuery 的强大功能:

var keywords = ["Tom", "Ohio"];
$(["Sally works at Taco Bell", "Tom drives a red car", "Tom is from Ohio", "Alex is from Ohio"]).filter(function(k, v) {
    return v.match("(" + keywords.join("|") + ")");
});

回答by Alex Turpin

You could use the [filter][1]function, but either way you'll need to loop through both arrays. You can use indexOfto check if a string is contained within another string.

您可以使用 [filter][1]函数,但无论哪种方式,您都需要遍历两个数组。您可以使用indexOf检查一个字符串是否包含在另一个字符串中。

var arr = ["Sally works at Taco Bell", "Tom drives a red car", "Tom is from Ohio", "Alex is from Ohio"];
var keywords = ["Tom", "Ohio"];
var filtered = [];

for(var i = 0; i < arr.length; i++) {
    for(var j = 0; j < keywords.length; j++) {
        if (arr[i].indexOf(keywords[j]) > -1) {
            filtered.push(arr[i]);
            break;
        }
    }
}

console.log(filtered);

Live example

活生生的例子