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

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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

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 arr array using the keywords array in jQuery? In this situation it would filter out "Sally works at Taco Bell" and keep the rest.

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 keywords array then the data.log from the JSON object is filtered using the keywords array and then appended to the screen.

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

回答1:

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

without jQuery:

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


回答2:

jQuery's word for "filter" is 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) }) 


回答3:

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

(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); 


回答4:

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.



回答5:

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

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



回答6:

Using jQuery awesome powers:

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("|") + ")"); }); 


回答7:

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/



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