Search code examples
javascriptarraysreactjsfor-loopjavascript-objects

Filter array of objects based on values in another array


I have an array of strings like this:

let countries = ["PT", "ES", "FR"];

and an array of objects that looks like this:

let people = [
               {name: "Tom", country: "ES"}, 
               {name: "Amy", country: "FR"}, 
               {name: "Bee", country: "US"},
               {name: "Ava", country: "PT"},
               {name: "Kim", country: "JP"}
             ];

I need a function that receives the array of countries and returns an array with only the people that have a matching country to ANY of the countries in the array.

With the arrays above, if I passed them into a function, I want it to return an array with only Tom, Amy and Ava, because only them are from countries that are present in the countries array. Bee and Kim are not included.

How can I do this? /: I tried using .filter on the array but I could only do it while hardcoding the values of the countries and I can't do that because the array of countries can change. If I pass an empty array, it should just adapt and return an empty array as well.

const matchCriteria (countries) => {
// Can you help me please make such function?
}


Solution

  • Simple as that:

    const countries = ["PT", "ES", "FR"],
          people = [
           {name: "Tom", country: "ES"}, 
           {name: "Amy", country: "FR"}, 
           {name: "Bee", country: "US"},
           {name: "Ava", country: "PT"},
           {name: "Kim", country: "JP"}
         ],
         
         
         result = people.filter(({country}) => countries.includes(country))
         
    console.log(result)