简体   繁体   English

如何将嵌套数组与常规数组进行比较?

[英]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"如果 DomArray 包含“声明”&&“匹配”但不包含“排除”中的内容,我想要的输出将是匹配项的数组

expected output:预期输出:

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

You can use a mix of filter and includes functions of Array to achieve this.您可以混合使用filterincludes Array功能来实现此目的。

 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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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