• Breaking News

    Real-time search using basic JavaScript

    The concept is quite simple. To conduct a search filter, we need something to search from.

    A list of sorts which has a collection of strings from which the user will search. It’s quite understood that we need to use an array for this in JavaScript.



    We can grab a Table Of Contents template as a use case. An element where we have a collection of relevant sections and their corresponding links.

    So, now we have an array of strings to search from.

    We need to make a function that can fetch all the relevant strings from the array based on the user’s search query. And this function needs to be called for every letter the user types.

    Based on the result of this function, we need to change the view and display the result on the screen. That is the concept behind a real-time search.

    The fundamentals

    This JavaScript code is simple and doesn't use any third party library.

    First, we need to define our TOC object containing a key-pair (relevant text and link), basically a plain JavaScript array:

    let toc = [
               ["Brief Description","#paragraph_1"],
               ["Core Text","#paragraph_2"],
               ["Conclusion","#paragraph_3"]
             ];
    
    Second, using the "map()" function to iterate each element of "toc" array, we will search for all the entries that match our search expression. 

    let newArr = toc.map((val,index,arr) => {
       if(val[0].toLowerCase().indexOf(query.toLowerCase()) != -1) {
          ....
       }
    });
    Finally, we will wrap up these elements into a simple function.

    A working sample

    Here you have a simple example of how real-time search is implemented in javascript: SEARCH SAMPLE


    No comments