简体   繁体   中英

How to compare nested array with regular array?

I have these two arrays, one is a nested array and one is a regular array. both containing strings. I need to go through the regular array and assess if the elements match only the "claims" key and "matches" key but NOT the exclusions key. What is the best way of doing this ?

 const claimsArr = [ {claim:'Protein',matches:['high in protein','^protein'],exclusions:['whey','milk']}, {claim:'Carbs',matches:['high in carbs','^carbs'],exclusions:['sugar','lactose']}, ]

 DomArray = [ "Protein", "whey" , ]

My desired output would be an array of matched items if the DomArray contains whats in "claim" && "matches" but not "exclusion"

expected output:

 result = ["Protien", "whey", "high in protein" ,"protein"]

You can use a mix of filter and includes functions of Array to achieve this.

 const claimsArr = [ { claim: 'Protein', matches: ['high in protein', '^protein'], exclusions: ['whey', 'milk'], }, { claim: 'Carbs', matches: ['high in carbs', '^carbs'], exclusions: ['sugar', 'lactose'], }, ]; const DomArray = ['Protein', 'whey']; const isAMatch = (str) => DomArray.some(dom => str.toLowerCase().includes(dom.toLowerCase())) const result = claimsArr.reduce((a, c) => { const matches = [c.claim, ...c.matches].filter(isAMatch); a.push(...matches); return a; }, []) console.log(result)

const claimsArr = [
  {
    claim: "Protein",
    matches: ["high in protein", "^protein"],
    exclusions: ["whey", "milk"],
  },
  {
    claim: "Carbs",
    matches: ["high in carbs", "^carbs"],
    exclusions: ["sugar", "lactose"],
  },
];

const DomArray = ["Protein", "whey"];
const Result = [];
const data = claimsArr
  .map((x) => [x.claim, x.matches])
  .flat(2);

for (let i = 0; i < DomArray.length; i++) {
  if (data.includes(DomArray[i])) {
    Result.push(DomArray[i]);
  } else {
    continue;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM