Filtering through an Array of Countries using .filter()

Lindsey Kopacz
InstructorLindsey Kopacz
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

We are going to use the the .filter() method on an array of countries so that we only return the country that matches a particular country code. This could be useful if you are in multinational organization and you want to return data only from that country's page.

Instructor: [00:00] Here we have a variable called Country Code and that is UK. Right below that we have variable named Countries that is an array of objects. In each object, we have a city, a country code, and then a latitude and longitude.

[00:19] If we go through all these data points, you see that there's countries in France and in Germany. Our goal here is to only return the values with a code of UK.

[00:32] Let's go ahead and get started and create a variable. Let's call this English Cities, and then we're going to take the countries and filter through that. What we're going to do now is we're going to pass it a callback.

[00:50] What we want to do here is we want to say if country.code equals country code then return country. If we save that and refresh this here and then type in English Cities, we now have what we want.

[01:17] The nice thing here is if we are returning country, when the country code equals country code, we can actually simplify this quite a bit.

[01:26] We can take away these curly brackets and the if statement, and we can take away the next curly bracket and have it be all in one line. Now if we refresh this and type in the same thing, we still get the same result.

egghead
egghead
~ 11 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today