Searching algorithm is a common pattern we need to be familiar with building dynamic web applications.
In this blog I will walk you through implementing a basic string search functionality which you can use in your web app.
To begin with, we need to familiarize ourselves with JavaScript's filter function
A filter function works based on the return value of the function passed
- filter accepts a function and provides all the items in an array as an argument
- for each element in an array it looks at the value ie. either true or false return from the function
- hence we can implement the validation logic in the function that is passed inside the filter method
For example:
let names = ['John', 'Kate', 'Ron'];
let newNameList = names.filter(i => true);
console.log(newNameList); >>> [ 'John', 'Kate', 'Ron' ]
let anotherNameList = names.filter ( i => i !== 'Kate' )
console.log(anotherNameList); >>> [ 'John', 'Ron' ]
Now that we are familiar with the filter function, let's turn our attention to the Data Structure
We will be using the following Data structure
const users = [
{ userName: 'John', id: 1001},
{ userName: 'Rob', id: 1002},
{ userName: 'William', id: 1003},
{ userName: 'Kate', id: 1004},
{ userName: 'Jim', id: 1005},
{ userName: 'Greg', id: 1006},
];
Please note your API or Application might have its own data structure, so you need to take it into consideration before you implement the following code
The search function is as follows
function findUserInfo(userName, searchString){
return userName.toLowerCase().substr(0,searchString.length).includes(searchString.toLowerCase());
}
the above function takes userName & searchString as its argument, which means we need to pass the userName from the users object and the search string obtained from the form input of search bar
the main objective of the findUserInfo function is to compare the search string obtained from the search bar with the user name and return true or false based on the match
userName.toLowerCase().substr(0,searchString.length)
the above code snippet from the function converts the user name to lower case and creates a sub string out of it based on the string length of the search term
includes(searchString.toLowerCase())
the above code snippet compares the result of first code snippet and determines whether the string includes a certain value among its entries, returning true or false as appropriate
so we chain together both code snippets as follows
userName.toLowerCase().substr(0,searchString.length).includes(searchString.toLowerCase());
Finally, we pass the result of the findUserInfo function to the filter function as follows
let searchResult = users.filter(i => findUserInfo(i.userName, '<search_string>' ))
The search result gets the object containing the specific userName from the users object. You can use this to display appropriate information to the end user as per the applications requirement.
Top comments (1)
Thx, it helped me