Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Filtering through an Array of Countries using .filter()

    Lindsey KopaczLindsey Kopacz

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.