Search Engine Application Using filter() and find() Functions in Underscorejs

in #utopian-io6 years ago

jquery6.JPG

Repository

Jquery in GitHub

Sammy.js in GitHub

UnderscoreJs in GitHub

My GitHub Profile

Search Engine Application Using filter() and find() Functions in Underscorejs

What Will I Learn?

  • You will learn to access the fake data by using the get() function.
  • You will learn filter() and find() functions in underscorejs.
  • You will learn includes() fuction.
  • You will learn text-centerclass in bootstrap.
  • You will learn load() and append() functions in jquery.
  • You will learn toLowerCase()function in javascript.

Requirements

Visual Studio Code in GitHub

Difficulty

  • Intermediate

Tutorial Contents

In this article I'll show the use of the find () and filter () functions on an example application. To be able to create an example, it must be a list of data.

I will list this data from scratch according to the search criteria entered in the input, and explain the properties of the find() and filter() functions.

I'll put the data into the page using the ajax get() function.

I will perform the search criteria using the includes() function. You will learn to use the find() and filter() functions as well as the ajax get() and includes() functions.

Underscorejs the filter() function returns all the elements in that provide the desired properties of the array.

Underscorejs the find() function returns the first value of an array that provides the desired properties.

Let's create the application step by step

The steps to implement are below:

  • Designing the index.html page
  • Defining get() function
  • Defining filter() function
  • Defining find() function
  • Routing operations

STEP 1:Designing the index.html page

The index.html page will have one input to perform the search criteria and two buttons. I will use the filter() and find() functions when I click on the buttons.

I will place the page that will be the result of the routing process at the bottom of the index.html page.

I will use the bootstrap library in the design of the page. We need to load the jquery, sammy.js, and underscorejs libraries into the page along with the bootstrap. I will use sammy.js for routing operations.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="./jquery.js"></script>
    <script src="./sammy.js"></script>
    <script src="./underscore.js"></script>
    <script src="./script.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <title>Find and Filter</title>
</head>



Now we can design the page.

I will use the <a> tag to perform the routing operations, but I will get the button feature. I will also center these buttons according to the area they are in.

If we want to center a text with bootstrap, we can use the text-center class.

<body>
    <div class="container">
        <div class="jumbotron text-center">
                <h2>Onepice Search Engine</h2>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <input class="form-control" id="inputSearch" type="text"/>
                </div>
            </div>
        </div>
        <diV class="row">(html comment removed: divided into two)
            <div class="col-md-6 text-center">
                <a href="#/search" class="btn btn-primary" id="btnSearch">Search</a>
            </div>
            <div class="col-md-6 text-center">
                <a href="#/lucky" class="btn btn-primary" id="btnLucky">I'm Feeling Lucky</a>
            </div>
        </diV>
        <br/>
        <div class="row">
            <div class="col-md-12">
                <div id="content"></div>
            </div>
        </div>
    </div>
    
</body>



Screenshot 1

jquery1.JPG

STEP 2: Defining get() function

When the Search button is clicked, the filter() function will return in the data and when I'm Feeling Lucky button is clicked, the find() function will return in the data.

In order to do these, I need datas.

We will retrieve our data from the JSONPlaceholder website.
JsonPlacHolder is a website that offers fake data free of charge. It contains many addresses that offer different data. We can use any of these addresses for our data.

In the script.js file I access the data using the ajax get() function.

$.get("https://jsonplaceholder.typicode.com/posts", function(datas, status){
       console.log(datas); //I will print data to console 
    })



Screenshot 2

jquery2.JPG


100 objects containing id, title, body and userId are assigned to datas variable.

We can check the status of the connection with the status variable.

STEP 3: Defining filter() function

When we click on the search button we must insert the data into the filter() function.

The value of the input value is checked with the includes() function to see if the data exists in the title.

The includes() function finds if there is another string value in an expression.

After doing these operations, we have a problem. Jquery has a case-sensitive structure. If the value entered in input is written in upper case letters, the desired result will not occur.

To overcome this problem, we can convert the input value to lower case.

The toLowerCase() function converts all characters in a string to lower case.

Let's create one filter variable and write the search button click event.

$('#btnSearch').click(function(){
            var searchWord=$('#inputSearch').val().toLowerCase();//We lower case the input value and assigned it to the searchWord variable.

            console.log(searchWord);//I will searchWord data to console
            filter= _.filter(datas,function(data){

                return data.title.includes(searchWord);//we searched within the title
            })
            console.log(filter);//I will print filter to console
        });



Screenshot 3

jquery3.JPG

Screenshot 4

jquery4.JPG

I listed the titles in the occ text.

STEP 4: Defining find() function

I will do the same things we did in the filter function. we will just write the find() function instead of the filter() function.

With the find() function we will return the first data.

$('#btnLucky').click(function(){

            var searchWord=$('#inputSearch').val().toLowerCase();//We lower case the input value and assigned it to the searchWord variable.

            console.log(searchWord);//I will searchWord data to console
            find=_.find(datas,function(data){
                return data.title.includes(searchWord);
            })
            console.log(find);//I will print filter to console
        });



Let's write input occ and click on the I'm feeling lucky button.

Screenshot 5

jquery5.JPG

STEP 5: Routing operations

We can now route the console prints to the page by doing routing operations.

I need to redirect pages using the load() function. I create search.html and lucky.html pages.

I will print the title and body fields of the data on the screen using the bootstrap panel on both pages.
so let's add a page <ul> tag. In lucky.html and search.html

<div>
        <ul>
            
        </ul>
            
</div>



I will add panel fields to these <ul> tags using the append() function.

var app = $.sammy(function () {

            this.element_selector = '#content';//area to show pages

            this.get('#/search', function (context) {//routing to search.html page
                
                context.$element().load('search.html',function(){
                    for (let index = 0; index < filter.length; index++) {//because there is more than one data
                        
                        $('ul').append('<div class="panel panel-info"><div class="panel-heading">'+filter[index].title+
                    '</div><div class="panel-body">'+filter[index].body+'</div></div>');
                        
                    }
                });
            });

            this.get('#/lucky', function (context) {//routing to lucky.html page
                context.$element().load('search.html',function(){
                    $('ul').append('<div class="panel panel-info"><div class="panel-heading">'+find.title+
                    '</div><div class="panel-body">'+find.body+'</div></div>');
                    })
            });
    
    
        })
        
        app.run('#/');



I used the for loop because the result of the filter operation is multiple data.

I wrote the body and title properties of the panel, as the filter and find variables have body and title fields.

As a result I have two different pages on the same page as the routing operations and I have arranged these pages using the callback function of the load function.

More information on routing operations with jquery here
Screenshot 6

When the search button is clicked
jquery6.JPG


Screenshot 7

When the I’m feeling lucky button is clicked
jquery7.JPG

Curriculum

Routing Operations with Jquery and Sammy.js

Proof of Work Done

https://github.com/onepicesteem/Search-engine-application-using-filter-and-find-functions-in-underscorejs

Sort:  

Thank you for your contribution.

  • Don't repeat code from previous tutorials, it's better to place the link of the tutorial and indicate which step should be viewed.
  • The difficulty of the tutorial should be basic.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Hey @onepice
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.31
TRX 0.11
JST 0.034
BTC 64332.82
ETH 3146.25
USDT 1.00
SBD 4.17