Search / filter an array
I am making a search function for an array. I have an entry [text] where for example I put "ban", then I need all results starting with "ban" to show, for example, banana, banana milkshake, banana (fried), etc.
How should I do it? I tried, but every time I try it is not accurate. What I have tried is below.
What do I have:
var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
inputBox.onkeydown = function(evt) {
$("#autocomplete").empty();
// INSERT CODE FOR SEARCH FUNCTION
}
I had one that came very close, however when I typed "ban" he came up with "Aardbei". This is obviously wrong. Here it is, maybe I missed something?
var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];
inputBox.onkeydown = function(evt) {
$("#autocomplete").empty();
var input, filter, a, i;
input = document.getElementById("myInput");
filter = inputBox.value.toUpperCase();
for (i = 0; i < ingredienten.length; i++) {
a = ingredienten[i];
if (a.toUpperCase().indexOf(filter) > -1) {
//console.log(a);
$("#autocomplete").append("<li>" + a + "</li>");
} else {
}
}
source to share
I think you should use event keyup
instead, and you can use regex and function filter
on an array of elements:
var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
inputBox.onkeyup = function(evt) {
$("#autocomplete").empty();
var query = $('#ingredient').val();
// escape regex
query = query.replace(
/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"
);
var queryRegExp = new RegExp('^' + query, 'i');
var results = ingredienten.filter(function(item) {
return queryRegExp.test(item);
});
results.forEach(function(item) {
$("#autocomplete").append("<li>" + item + "</li>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ingredient" />
<div id="autocomplete"></div>
source to share
Using jQuery UI autocomplete this task can be done very easily:
$('#ingredient').autocomplete({
source: ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<input id="ingredient">
source to share
Following the instructions, you can use the regex filter here in your array.
const results = ingredienten.filter(item => item.match(/^ban/)); //add i at the end to ignore case
This will iterate over the array and return all results that match the regex, "starts with" disallow.
You can also do the 0-2 substring match == 'ban', but a little more manual.
source to share