How do I take an array of strings and filter them?
Solution 1
$.grep( arr, $.proxy(/./.test, new RegExp(keywords.join("|"))));
without jQuery:
arr.filter(/./.test.bind(new RegExp(keywords.join("|"))));
Solution 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) })
Solution 3
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.
Solution 4
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);
Related videos on Youtube
amlane86
A little bit of this, a little bit of that, but mostly just try to stay out of trouble. ;)
Updated on June 04, 2022Comments
-
amlane86 almost 2 years
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 thekeywords
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 thekeywords
array then thedata.log
from the JSON object is filtered using thekeywords
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.
-
kapa over 12 years@Xeon06 The jquery tag was fine, it indicates that the OP accepts solutions based on jQuery methods.
-
-
Richard Neil Ilagan over 12 years... and I seriously have to think of regex'es top of head. nicely done. :D it'd be nice to slap it on with the
$.grep()
function though. +1 -
jondavidjohn over 12 years+1 very nice solution, write out the loop, and no jQuery needed :D
-
Chris Pratt over 12 yearsBest answer here in my opinion, even though it does borrow somewhat from mine ;).
-
jondavidjohn over 12 yearsMight want to include a
hasOwnProperty()
if you're usingfor..in
I would honestly just use a regularfor
, you are dealing with arrays not objects. developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… -
Esailija over 12 years@qwertymk well I have only tested in IE7 and chrome, no reason it wouldn't work in other browsers though. If you are using the second one in a legacy browser you need to shim
.filter
and.bind
from MDN for example. -
georg over 12 years@ChrisPratt: I didn't borrow anything.
-
mozzbozz over 9 yearsI am using this in Qt / QML to filter the content of a ComboBox depending on the text in the TextField next to it: Works like charm, just one line of code for filtering and it's really fast (no noticeable delay; got about 500 Strings to be filtered). First tried to adapt some bloaty typeahead javascript libraries but could not get it work. Your one line of code: Perfect -> Thanks! :D