Day 12 - Making A Search Function: Rest Countries Part II
Joanne
Posted on September 25, 2020
Today I worked on building the filter, search and header components of my rest countries API. So far so good!
What I Learned
Given a search value, I use the function below to filter names typed in search bar component.
It helps suggest some countries I am looking for. But it doesn't take into account to search the letters in order so I wanted to refine this. So if I search 'n' any country with an 'n' in it will be returned. If I continue typing to 'ne' regardless of the order, any countries with 'ne' within itself will be returned.
What's happening? The indexOf method looks for the search value inside the word of each name. If the letters it is looking for is inside the word - regardless of where it appears in the word - it will return the index. The issue is that it doesn't check if the first letters of the name match the first letters of the search value. As a person, if I am looking for the Netherlands, I expect to type 'ne' and assume the Netherlands will appear as one of the top answers.
So I created a function that uses the slice method. It will check if the first set of letters of each country name match the search value and if it does, it could be a match so return it. I use this function to filter matches before mapping the countries to the child component.
And it looks like it is doing what I want it to do!
Onto the next challenge!
Posted on September 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024