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.
$.grep( arr, $.proxy(/./.test, new RegExp(keywords.join("|"))));
without jQuery:
arr.filter(/./.test.bind(new RegExp(keywords.join("|"))));
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) })
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With