I am getting back the following array below and would like to show all the matched objects based off the matched strings.
Returned Array: ["USA", "FRA", "GBR"]
Original Array:
export const COUNTRY_CODES = [
{
country: "United States of America",
code: "USA",
},
{
country: "Albania",
code: "ALB",
},
{
country: "Algeria",
code: "DZA",
},
{
country: "France",
code: "FRA",
},
....
]
My desired Output is to show the country that matches:
["United States of America", "France"]
JS:
const flatArr = ["USA", "FRA", "GBR"]
COUNTRY_CODES.find((v) => flatArr === v.country)
CodePudding user response:
One method to achieve this is to use reduce
with includes
.
const COUNTRY_CODES = [
{
country: "United States of America",
code: "USA",
},
{
country: "Albania",
code: "ALB",
},
{
country: "Algeria",
code: "DZA",
},
{
country: "France",
code: "FRA",
},
];
const flatArr = ["USA", "FRA", "GBR"];
const matchedCountries = COUNTRY_CODES.reduce((matched, countryCode) => {
if (flatArr.includes(countryCode.code)) {
matched.push(countryCode.country);
}
return matched;
}, []);
console.log(matchedCountries); // ["United States of America", "France"]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>