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:
JavaScript
x
20
20
1
export const COUNTRY_CODES = [
2
{
3
country: "United States of America",
4
code: "USA",
5
},
6
{
7
country: "Albania",
8
code: "ALB",
9
},
10
{
11
country: "Algeria",
12
code: "DZA",
13
},
14
{
15
country: "France",
16
code: "FRA",
17
},
18
.
19
]
20
My desired Output is to show the country that matches:
JavaScript
1
2
1
["United States of America", "France"]
2
JS:
JavaScript
1
3
1
const flatArr = ["USA", "FRA", "GBR"]
2
COUNTRY_CODES.find((v) => flatArr === v.country)
3
Advertisement
Answer
One method to achieve this is to use reduce
with includes
.
JavaScript
1
30
30
1
const COUNTRY_CODES = [
2
{
3
country: "United States of America",
4
code: "USA",
5
},
6
{
7
country: "Albania",
8
code: "ALB",
9
},
10
{
11
country: "Algeria",
12
code: "DZA",
13
},
14
{
15
country: "France",
16
code: "FRA",
17
},
18
];
19
20
const flatArr = ["USA", "FRA", "GBR"];
21
22
const matchedCountries = COUNTRY_CODES.reduce((matched, countryCode) => {
23
if (flatArr.includes(countryCode.code)) {
24
matched.push(countryCode.country);
25
}
26
27
return matched;
28
}, []);
29
30
console.log(matchedCountries); // ["United States of America", "France"]