Skip to content
Advertisement

If all strings match in array then show matched object in Javascript

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)

Advertisement

Answer

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"]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement