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!
Top comments (2)
You can also use your initial
indexOf
way, but compare as=== 0
instead of!== 1
, unless I'm missing something.Ah yes, indexOf always starts at 0! Since I wanted to look at the beginning of string for the characters, this is a much shorter way to write out my search function. Thanks!