0

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)
user992731
  • 3,400
  • 9
  • 53
  • 83
  • Does this answer your question? [Filter array of objects based on another array in javascript](https://stackoverflow.com/questions/46894352/filter-array-of-objects-based-on-another-array-in-javascript) – pilchard Oct 24 '21 at 23:22
  • combined with [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – pilchard Oct 24 '21 at 23:25

1 Answers1

1

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"]
chipit24
  • 6,509
  • 7
  • 47
  • 67