The simple way to do it is to split your search text into individual words and check each one...
var searchWords = freeText.split(' ');
searchWords = CleanWords(searchWords); // This removes words like '&', '-', 'the'
for(var i = 0; i < searchDataList.length; i++){
for (var n = 0; n < searchWords.length; n++){
var word = searchWords[n].toLowerCase();
var title = searchDataList[i].ttl.toLowerCase();
if (title.indexOf(word) > -1){
// addItem = true;
}
}
}
If you don't want to do that then you could try pre build an index and check if the search words are in the index. Pseudo code below...
// Prebuild index
var index = {};
foreach(var item in searchDataList){
var words = item.ttl.split(' ');
words = CleanWords(words); // This removes words like '&', '-', 'the' etc
foreach(var word in words){
word = word.toLowerCase();
if (index[word]){
index[word].Push(item.no); // Build up array of search term indexes that contain this word.
} else {
index[word] = [item.no];
}
}
}
// Perform search
var searchWords = freeText.split(' ');
searchWords = CleanWords(searchWords);
foreach(var word in searchWords){
var matches = index[word];
foreach(var match in matches){
// Do something with matches
var matchedItem = searchDataList[match];
}
}
Also have a look at the following answer for more discussion on speed of accessing items by key on an object in JavaScript... Array vs. Object efficiency in JavaScript
You could also consider using var index = new Map();
rather than an object (I'm not sure if it is faster or not though).