I have made this simple search snippet. I made it to search throughout my array(elements array) and if the input value is exactly equal to one of the element's names and that element will return.
So here if we search 'apple' in the input field the below result will return
{ color: "red", name: "apple" }
My question is: Without returning according to the exact value of the input, can we return a value like the input value. For example, instead of typing 'apple' word when we type the starting letters of the 'apple' word like 'ap' I'm expecting to return apple object and apex object which includes 'ap' (I want to return all the objects which contain the name like 'ap' from the array) like a normal search function does. Thank you if somebody likes to help me.Below is my code.
//array
const elements = [{name: 'apple',color: 'red'},{name: 'apex', color: 'white'},{name: 'bat', color: 'black'}];
//find function
const searchElement = (elementsArray,keyword) => {
const returnedElement = elementsArray.find((element,index) => {
return element.name.toLowerCase() === keyword.toLowerCase();
});
return returnedElement;
}
//keyup event
document.getElementById('myInput').addEventListener('keyup', () => {
const keyword = document.getElementById('myInput').value;
const result = searchElement(elements,keyword);
console.log(result);
});
<input type="text" placeholder="Search" id="myInput">
apexdoes not start withapp.ap, which, again, is something "Fuzzy search" libraries can match.