Reputation: 1013
dataArray=[
'red|24|easy|simple',
'red|24|moderate',
'red|24|difficult|hard',
'black|24|difficult|hard',
'black|34|difficult|hard'];
I want to find all array items that match all of the words in my text box:
'red hard' - matches middle entry
'bl har 3' - matches last entry
'2 b d h' - matches 4th entry
It seems easy to find any 1 matching search term using jquery, but how do I find array items that match all terms as above.
Any help would be much appreciated.
Upvotes: 0
Views: 107
Reputation: 59232
Supposing data
array is a array of arrays, you can use Array.filter
in the following way.
Firstly, we will split the input string on spaces and using String.indexOf
, and then we will filter out the entry.
var matches = data.filter(function(str){
return input.split(/\s+/).every(function(elm){
return str.toLowerCase().indexOf(elm.toLowerCase()) > -1
});
});
Now, assuming that there can be more than one match, we are storing the filtered array in matches
. If you want to take the first result, then just do
console.log(matches[0]);
Upvotes: 1