Reputation: 276
I am trying to implement autocomplete to my application using Local Storage. Is there way to search inside an array of words using 'LIKE %value%' condition?
var autocompleteArr = ['two', 'three', 'twenty two', 'twelve'];
mySearchMethod(autocompleteArr, 'tw'); //['two', 'twenty two', 'twelve']
Upvotes: 0
Views: 97
Reputation: 11620
If you are interested in partial search use filter:
function match(value) {
return value.match(/.*tw.*/);
}
var filtered = ['two', 'three', 'twenty two', 'twelve'].filter(match);
// filtered is ['two', 'twenty two', 'twelve']
If interested in exact match, then indexOf
will do.
Upvotes: 3
Reputation: 111
You might want to do something like this
var autocompleteArr = ['two', 'three', 'twenty two', 'twelve'];
var autocomplete = function(word) {
return autocompleteArr.filter(function(ele) {return ele.match(".*"+word+".*");})
}
autocomplete("tw") // ["two", "twenty two", "twelve"]
http://jsfiddle.net/jkn6xgr7/2/
Upvotes: 1
Reputation: 2014
You can use indexOf to check if a string contains another.
var autocompleteArr = ['two', 'three', 'twenty two', 'twelve'];
function mySearchMethod(haystack, needle) {
arr = [];
for(var i = 0; i < haystack.length; i++) {
if (haystack[i].indexOf(needle)) {
arr.push(haystack[i]);
}
}
return arr;
}
Upvotes: 1
Reputation: 7900
You can achieve this combining regular expressions and Array.filter
:
var input = ... // get the user input from somewhere
var autocompleteArr = ['two', 'three', 'twenty two', 'twelve'];
var suggestions = autocompleteArr.filter(function(el){
return new Regexp(input).test(el);
});
If you want to match from the beginning of the typing, change this line to:
return new Regexp("^"+input).test(el);
Upvotes: 1
Reputation: 2251
function arrayContains(autocompleteArr, searchString){
var answerArray = [];
for(var i = 0; i < autocompleteArr.length; i++){
if(autocompleteArr[i].indexOf(searchString) != -1){
answerArray.push(autocompleteArr[i]);
}
}
return answerArray;
}
Upvotes: 1