Filtering through an Array of Countries using .filter()

Lindsey Kopacz
InstructorLindsey Kopacz

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 10 months 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.