Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search inside an array and return multiple results

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"
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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">

>Solution :

I think this is what you want. Use filter instead of it.

//array
const elements = [
    { name: "apple", color: "red" },
    { name: "apex", color: "white" },
    { name: "bat", color: "black" }
];

//find function
const searchElement = (elementsArray, keyword) => {
    const returnedElement = elementsArray.filter((element, index) => {
        return element.name.toLowerCase().includes(keyword.toLowerCase());
    });

    return returnedElement;
};

//keyup event
document.getElementById("myInput").addEventListener("keyup", () => {
    const keyword = document.getElementById("myInput").value;
    const result = searchElement(elements, keyword);
    result.forEach((item) => console.log(item.name));
});
<input type="text" placeholder="Search" id="myInput">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading