How to Filter Data (Object in Array) and Render the Output in the Browser Using JavaScript

How to Filter Data (Object in Array) and Render the Output in the Browser Using JavaScript

Introduction

A lot of improvement has occurred in human lifestyle through the evolution of technology. Tech has made it much easier to perform transactions and order goods from far away China, Europe and America using an online e-commerce store from the comfort of your house.

I believed you must have heard about or used e-commerce websites like Amazon, Aliexpress, Alibaba, eBay and a lot more to order your goods/products.

As a frequent user, you would have noticed that in the process of searching for your particular goods, you typed a keyword such as 'phone' on the search bar and filtered out millions of data showing only the ones related to phones.

As a developer or newbie in tech, If you have been brainstorming on how this was achieved, then you have come to the right place.

In this article, I will teach you how you can filter data from millions of data by just typing a keyword.

Pre-requisites

  • Knowledge of HTML

  • Basic understanding of JavaScript

  • Chrome Browser

  • Text Editor (Vs code preferably)

HTML Syntax

Firstly, you will need to set up your Html boilerplate which will include some elements like h1, h2, input, div which will all be used to structure your content.

Then, you will now introduce your script tag before the end of your body tag which will be used to link the html file directly with the javascript file.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Notes App</h1>
    <h2>Take Notes and never forget</h2>
    <input id="search-text" type="text">
    <div id="notes"></div>
    <script src="notes-app.js"></script>
</body>
</html>

The above code should display like this on your browser

Writing Out the JavaScript Code

Now that you have written out your HTML content and already linked it with the Javascript file, let's start writing our javascript codes.

Firstly, you will set up a constant variable that will be assigned with some objects that are embedded in an array which are going to serve as the data to be filtered whenever the user types a keyword.

const notes = [{
  title: 'lg phone',
  purchased: false
},{
  title: 'samsung phone',
  purchased: false
},{
  title: 'iphone',
  purchased: false
},{
  title: 'cake',
  purchased: false
},{
  title: 'fish',
  purchased: false
},{
  title: 'tecno phone',
  purchased: false
},{
  title: 'hp phone',
  purchased: false
},{
  title: 'lg phone',
  purchased: false
},{
  title: 'pie',
  purchased: false
}]

You will now create another const variable which contains an object with any empty strings.

const filters = {
  searchText: ''
}

Filtering and Rendering of data

Now, you will write some code syntax which will be used to search through the data in the notes variable and filter it according to the keyword entered by the user.

To achieve this, you will create a const variable like renderNotes which will contain a function with two arguments (notes and filters)

const renderNotes = function(notes, filters){
}

Inside this function again, you will create another const variable called filteredNotes which will be assigned another function with one argument (note) such that the newly created function will be used to search and filter through the data declared in the notes variable.

const renderNotes = function(notes, filters){
    const filteredNotes notes.filter(function(note){
    }
}

Then the function will be set to return the data that match the keyword typed by the user which is included inside the object's title and will be converted to lowercase using toLowerCase()

// filtering data
const renderNotes = function(notes, filters){
    const filteredNotes = notes.filter(function(note){
      return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
  })
}

Adding Data in Note.title as Content to Html Body.

Here you will now add the content of notes.filter to the mainbody of the HTML element using javascript.

Firstly, you will loop through the result of filteredNotes using a forEach which comes along with a function with only one argument (note).

// filtering data
const renderNotes = function(notes, filters){
    const filteredNotes = notes.filter(function(note){
      return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
  })
    //Adding Data content of note.title
    filteredNotes.forEach(function(note){
    })
}

Secondly, you will now create a new const variable such as NoteNewElement which will be assigned with the syntax used for creating a new element in javascript which is document.createElement().

// filtering data
const renderNotes = function(notes, filters){
    const filteredNotes = notes.filter(function(note){
      return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
  })
    //Adding Data content of note.title
    filteredNotes.forEach(function(note){
        const NoteNewElement = document.createElement('p')
    })
}

Then the text Content of NoteNewElement will be assigned to the text content of note.title using NoteNewElement.textContent. Now, Using appendChild each content of NoteNewElement will be added to the div tag in html body by using tag by ID.

The next step is to call back the function using renderNotes with two arguments (notes, filters)

// filtering data
const renderNotes = function(notes, filters){
    const filteredNotes = notes.filter(function(note){
      return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
  })
    //Adding Data content of note.title
    filteredNotes.forEach(function(note){
        const NoteNewElement = document.createElement('p')
        NoteNewElement.textContent = note.title
        document.querySelector('#notes').appendChild(NoteNewElement)
    })
}
renderNotes(notes, filters)

For data in notes.title to display on the browser, you will use document.querySelector('#search-text') to target the input ID which is search-text and then use addEventListener to listen to the input change

document.querySelector('#search-text').addEventListener('input', function(e){
    filters.searchText = e.target.value
    renderNotes(notes, filters)
})

As shown below, the paragraph element started recreating itself when a key is being typed by the user on the input search bar.

To avoid this, the ID of the note will be targetted and innerHTML will be used to set its initial content to empty.

// filtering data
const renderNotes = function(notes, filters){
    const filteredNotes = notes.filter(function(note){
      return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
  })

    //Setting the innerHTML to empty
     document.querySelector('#notes').innerHTML = ''

    //Adding Data content of note.title
    filteredNotes.forEach(function(note){
        const NoteNewElement = document.createElement('p')
        NoteNewElement.textContent = note.title
        document.querySelector('#notes').appendChild(NoteNewElement)
    })
}
renderNotes(notes, filters)

document.querySelector('#search-text').addEventListener('input', function(e){
    filters.searchText = e.target.value
    renderNotes(notes, filters)
})

Now let's run and test the code.

As shown above, you will see that the user types the keyword phone in the input search bar and only the data related to the phone inside our array was filtered and displayed on the browser.

Conclusion

Hurray!! I bid you a massive congratulations. You have successfully learned and understand the basic concept that is being used in most e-commerce stores to filter through their data with keywords typed by their potential user.

Instead of perusing from the electronic section to the clothing/fashion area to home appliances, this coding concept makes online shopping user friendly and it also saves them a lot of time.

Because of the high level of competition between various eCommerce stores, it is a must for a startup that aims to captivate the mind of users and achieve optimum growth within a few years to have a well-responsive website and mobile application.