DEV Community

Cover image for Day 12 - Making A Search Function: Rest Countries Part II
Joanne
Joanne

Posted on

Day 12 - Making A Search Function: Rest Countries Part II

Today I worked on building the filter, search and header components of my rest countries API. So far so good!

mobile view

What I Learned

Given a search value, I use the function below to filter names typed in search bar component.

index of

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.

example of search

Good. But could be better.

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.

sliced function

Alt Text

And it looks like it is doing what I want it to do!

new search

Onto the next challenge!

Top comments (2)

Collapse
 
katylava profile image
katy lavallee

You can also use your initial indexOf way, but compare as === 0 instead of !== 1, unless I'm missing something.

Collapse
 
joanne profile image
Joanne

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!