Home > OS >  Get object out of array if it contains value of another item in another array
Get object out of array if it contains value of another item in another array

Time:01-19

I have the following array of objects

  const raceOptions = [
    { value: "AmericanIndianOrAlaskaNative", label: "American Indian or Alaska Native" },
    { value: "AmericanIndianOrAlaskaNativeOther", label: "American Indian or Alaska Native Other" },
    { value: "Asian", label: "Asian" },
    { value: "AsianIndian", label: "Asian Indian" },

  ];

I also have another array that has

var incomingArray = ['Asian', 'AmericanIndianOrAlaskanPacific', 'NativeHawaiian', 'BlackorAfricanAmerican']

How can I create a new array of objects only if the incomingArray has values that match the raceOptions value?

If incomingArray contains 'Asian' I want a new array that will contain "{ value: "Asian", label: "Asian" }" which comes from the raceOptions array.

CodePudding user response:

Use Array#filter in conjunction with Array#includes.

const raceOptions = [
  { value: "AmericanIndianOrAlaskaNative", label: "American Indian or Alaska Native" },
  { value: "AmericanIndianOrAlaskaNativeOther", label: "American Indian or Alaska Native Other" },
  { value: "Asian", label: "Asian" },
  { value: "AsianIndian", label: "Asian Indian" },

];
let incomingArray = ['Asian', 'AmericanIndianOrAlaskanPacific', 'NativeHawaiian', 'BlackorAfricanAmerican'];
let res = raceOptions.filter(x => incomingArray.includes(x.value));
console.log(res);

  • Related