Skip to content
Home » How to create JavaScript list filter and search?

How to create JavaScript list filter and search?

  • by
JavaScript list filter

Creating a JavaScript list filter and searching for records is one of the fundamental skills for web developers.

Filtering means that we make a list of records shorter, more adjusted to the user’s wishes, using some known values.

Search means that we are using unknown search terms to find records in the list, or database. We are used to searching so much that a lot of pages offer just search, without filtering, categories. We show you how to use both, which technique you will use, is up to you. 

How can we filter and search in JavaScript using:

  • Array.filter
  • Array.find
  • loops
  • Array.includes
  • Array.findIndex

First, we explain the functions for filtering and searching for records, then we have a more in-depth example, how you can use this knowledge when building your web site.

The filter function in JavaScript

We have a great function to create a JavaScript list filter for an array, named filter(). The filter works with an array, and we can use it on most data structures.

JavaScript filter function

JavaScript

JavaScript filter function

Calling the filter function on an array does not change the array, but returns a new filtered array. For the callback function, we can use an inline function or as in our example a function called isBiggerThanFive

JavaScript list filter - Is bigger than

JavaScript

JavaScript list filter - Is bigger than

In the callback function, you can test a condition and return a true or false value.

Search using the find function in JavaScript

find() function is useful when we need to find a single element that conforms to a condition. If we take a look at the same example with numbers from 0 to 9, this will return a number 6. 

JavaScript find function

JavaScript

JavaScript find function

For the callback function, we use the same function isBiggerThanFive (see above) to return if the number is bigger than 5.

We can use the find() function, for example in a JavaScript list, to filter elements using an ID. 

In the end all the types of searching will give you an object (or array), if you are new to JavaScript and want learn more about objects read our blog post: What is an Object in JavaScript.

What happens if find does not find any element

It is very important to know, that there is a possibility that the find method does not return any elements. What happens then?

JavaScript find function - no elements found

JSON

JavaScript find function - no elements found

When an element is not found, the find() function returns value undefined.

Implement JavaScript list filter using loops

If we want, we can implement all filtering and search functions using loops as well. We would advise you to use JavaScript native functions, but using loops is great to learn more about how things work in the background.

Sometimes it is also useful to use loops if we need to calculate some other aspects based on data within the array or list of elements.

Filter array with loops

JavaScript

Filter array with loops

Here we show how we can filter numbers that are bigger than 5 using a plain and simple for loop (you could also use other loops like forEach, check our blog post about loops in JavaScript to learn more). 

With for loop, we iterate all 10 elements in the array. Within each iteration, we need to find elements using an index. At the end of the iteration, we test the condition.

We need to create a result ourselves using for loop. This is why we introduced the resultArray that holds all the elements that meet the condition. We add elements using the push method.

The benefit of using a loop is that we can add more instructions if the condition is met. In our case, we added a counter (count) that will count all the bigger numbers.

Check if the array contains elements using includes function

We can check if an array contains elements using includes() function. This is very similar to find function but it only returns a true or false value based on the presence of the element using given conditions.

JavaScript includes method

JavaScript

JavaScript includes method

This time we only check if number 5 is in the array. The function returns true.

Using includes is very useful to check if the ID of a user or some other object is contained in the list of IDs in the group. We can also check if the selected option is part of options when a user enters a value.

Get the index of an element using findIndex

Sometimes we just need an index of elements, we can use findIndex for that. In a sense, it works like find but returns only the index. Imagine that you have two arrays with similar data one is for user data the other for user subscription both in an array. User data is on the same index as subscription data, and you can use the index for users to access subscription data.

JavaScript findIndex method

JavaScript

JavaScript findIndex method

But beware that numberIndex is not the real number value but index. We need one more step to read the number value. 

Get the number from array using index

JavaScript

Get the number from array using index

We access the value of the number using the index on the array.

Now that we know the theory we can use all that knowledge in an example.

JavaScript list filter example

Our JavaScript list filter example is split into two main examples:

  • Filter list, using search field
  • Filter list, using a dropdown list (select)
JavaScript search UI with dropdown

We like to showcase functions using a list of music bands since we all like to listen to music and have some fun. Also, you can easily add your favorite bands as well.

Fundations of our page and how we load data

There are a few basic functions that our web page needs to work properly. For example, loading data and showing data after web page loading is done. These functions are not search functions but they help us to load data and show records on the web page.

JSON data for the bands

Our web page will have a search and we need some data to search in. Here is some JSON data for the bands, we will use it in our filtering examples. Copy the data and store it in a JSON file within your web page, we named our file bands.json.

The data - List of albums

JSON

The data - List of albums

Keep in mind that in this picture the data of a few bands are folded to make the image smaller.

Loading data for the web page 

First, we add a variable, that will store all the bands we have in our JSON file

Initialize bands variable

JavaScript

Initialize bands variable

loadData is a function that will load data from a specified file. It uses the window.fetch method to load data (for this example data is stored locally, but this could also be an API with data fetched from a server)

Load data from assets (file) or URL

JavaScript

Load data from assets (file) or URL

We use loadData in the loadBands function.

Load the bands data - loadBands function

HTML

Load the bands data - loadBands function

This function specifies the name of the JSON file and a function that is called when loading is done.

The last function for loading is called storeBandsLocally data stores bands in a variable and calls functions to show data.

Temporary store bands data

JavaScript

Temporary store bands data

This function also contains a call for the fillDropDown method.

We need some HTML elements on the web page for fillDropDown to work. You have an explanation on which tags to use, below.

First, we get the reference for the HTML element using the document.getElementById method. We use the bandsDropdown ID.

Filter dropdown - fillDropDown function

JavaScript

Filter dropdown - fillDropDown function

To add list options we iterate over all the bands using the forEach loop. Within every iteration, we create a new option element.

For label and name property, we use the band name. In more complex examples value property is the usual ID of some kind, to easily link to a record using an ID. 

It is nicer to select one of the records at the beginning. We do this by setting the selectedIndex property.

JavaScript list filter JS 24

Setting the value to 0 will select the first record since the index is zero-based.

Now that we have a band selected we can call showSelectedBand() function and display data for the band that is in the first position. 

Creating HTML for search field and results

JavaScript list filter HTML 03

The first example shows how to use the search field to filter lists, using JavaScript. You can see how this search field looks like on our web page.

The HTML for the input and for showing results looks like this.

Building UI - Let's add a search field and a search button

HTML

Building UI - Let's add a search field and a search button

The first element we use is the input tag and we set the type to text. We also add the to set the id attribute value. We need the id so that we can use this element in JavaScript to find the element in the document. The button has an onclick attribute with our function we call searchWithField

At the end, there is an unordered list, ul tag that displays all the bands our search string filters.

Using search field to filter list in JavaScript 

Search with input field - serchWithField function

JavaScript

Search with input field - serchWithField function

First, we need to get references for HTML elements using the getElementById method and provide IDs we used in HTML. 

In variable ul we store reference for the unordered list with ID bandsFound. This list shows all the bands our search finds.

Next is field variable, that stores reference for HTML input tag element with id searchField. We need to read value stored in our search input field. We do this with a value method.

JavaScript list filter JS 17

Beware that we just use the search function here, the search function does all the filtering for us and by calling it we get a filtered array as the response. The explanation for the search function is below.

JavaScript list filter JS 16

In sense storing a value in bands variable is all we have to do to get filtered array bands.

Now we focus on showing the records.

At the beginning, we set innerHTML to empty string this a little hack we use to clean up if there are any results from previous search already stored in our unordered list. You could also remove list items one by one.

The last step is to iterate through all the bands.

JavaScript list filter JS 18

For each band, we create a new list item with the document.createElement method, this method creates an HTML element using the name of the desired tag.

When we set innerText value for list item we use JavaScript template literals so remember to use backtick instead of an apostrophe. Using literals we can easily format the string output and add values for each band.

Don’t forget to append new list item to the unordered list at the end.

How to make text search function in JavaScript

The search function leverages both the filter method and includes the method we talked about before. Filter function filters bands, but we use includes to search for text in the band values (etc. in the name of the band.

Search the text in data - search function

JavaScript

Search the text in data - search function

We start with a check that makes sure there is a string search present. In other cases search function returns all the bands.

JavaScript list filter JS 19

Next we convert searchString.

JavaScript list filter JS 20

We use toLowerCase to make our search case insensitive, for that we need to make both search string and all the values lowercase.

We get filtered values using the filter method on the bands variable. This method iterates over all the bands and for each band we have a custom call that checks all the conditions.

First, we check if the band name or band description contains searchString. We do this using includes method.

JavaScript list filter JS 21

If any of the conditions meets the criteria we need to return the true value.

Searching arrays within arrays

For illustration, we also added a criteria that checks if any of the albums the band recorded, contains our searchString. For that, we need another filter, that filters the bands’ albums.

JavaScript list filter JS 22

At the end, we check if filteredAlbums contains any records and if it does we return the true value.

Remember to finish the search function using the return filtered. This returns all the bands that we found.

Adding drop-down list for selecting bands to the web page

JavaScript list filter HTML 04

The dropdown list or HTML select tag is a nice way of letting users choose a subset of records.

UI - Let's add a dropdown selector

HTML

UI - Let's add a dropdown selector

First, we add a select tag, we need to add an id bandsDropdown. The next important thing is to capture the event when the user changes the value. We do this using an onchange event.

We put the result of the selected band into the div tag and we add the id attribute bandSelected. 

Now, we are now ready to use prepared elements and make a JavaScript list filter.

Implement JavaScript list filter with dropdown list

Show band that user selected - showSelectedBand function

JavaScript

Show band that user selected - showSelectedBand function

We need to store references to our HTML elements first using the getElementById method. Read more about how to createElement in JavaScript.

In the dropdown variable, we store the reference for the select tag with the bandsDropdown id. In the bandSelectedDiv variable, we have a reference for the div tag that shows the band.

This time we use the find method to find the first band that meets the criteria. Find works in a similar way like the filter, but it returns only one record. We check only if the band name equals the value of the dropdown selection. We can do that since we also added the band names for values of the options listed in the dropdown list.

If the band is found we create a result with the HTML formatting within the string literals. We change the HTML value of the bandSelectedDiv using the innerHTML property. innerHTML differs from innerText because it enables us to format values as well. In our case, we make the name of the band bold.

Conclusion about searching and filtering data

There are many functions already available for us in order to implement list filters in JavaScript. Most of them are out of the box and ready to use. They offer callback calls for custom implementations of how conditions are checked.

If you know how to use the filter and the includes function, you have most of the knowledge needed to implement most searches out there. 

Have fun coding with CodeBrainer!