Reputation: 37
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"]
Upvotes: 0
Views: 72
Reputation: 879
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)
Upvotes: 1
Reputation: 1658
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;
}
}
Upvotes: 1