javascript - 灵活匹配两个阵列
问题描述
我在一个应用程序 Ionic 上工作,其中包含配料和带有食谱的服务,看起来像这样->
所以我需要把配料和食谱搭配起来。我开始这样做:
this.truelist = [...this.spliterStrIngredients()]; // my arrayof ingredients
const nbIngredients = this.truelist.length;
console.log('true list = ' + this.truelist);
let match = 0 ;
this.recipeList.forEach((key => {
key.ingreds.forEach(ingrRecipe => {
this.truelist.forEach((ingrSelct , index) => {
if (ingrSelct === ingrRecipe)
{
match ++;
}
if (match >= this.truelist.length ) {
this.recipeMatch.push(key.name);
match = 0;
}
});
});
}));
console.log(this.recipeMatch);
}
因此,当我选择完全相同的食谱但我希望更灵活时,它可以工作,例如我有意大利面+奶酪+胡萝卜阵列,但我可以搭配 carbonara。
谢谢您的帮助
解决方案
按照您提出的规则,这里有一个适合您需求的解决方案:
const recipeList = [{
name: 'Carbonara',
picFile: '',
ingreds: ['Pasta', 'Cheese', 'Egg'],
description: ['1', '2', '3']
}];
const myIngredientsA = ['Pasta', 'Cheese'];
const myIngredientsB = ['Pasta', 'Cheese', 'Egg'];
const myIngredientsC = ['Pasta', 'Cheese', 'Egg', 'Bacon'];
function findMatchRecipe(myIngredientsList: string[]) {
let count = 0;
let recipeMatch: any[] = [];
recipeList.forEach(recipe => {
recipe.ingreds.forEach(ingredient => {
if (myIngredientsList.includes(ingredient)) {
count++;
}
});
if (count === recipe.ingreds.length) {
recipeMatch.push(recipe.name);
}
count = 0;
});
console.log(recipeMatch);
}
findMatchRecipe(myIngredientsA); // doesn't find a match, since the 'Egg' is missing
findMatchRecipe(myIngredientsB); // finds a match, since all ingredients match
findMatchRecipe(myIngredientsC); // finds a match, since all ingredients match independent of the extra ones
推荐阅读
- python - Python - 如何不以科学计数法获得指数(例如 1.2**1000 = 1.5179100891722457e+79)
- c++ - 使用 unique_ptr 作为类成员变量
- android - 弹出的 React Native 应用程序无法访问 Firestore 后端
- google-apps-script - 查找范围内的单元格
- sql - Postgres 父子网络 ID
- python - 无法理解python中的负字符串切片
- java - 检查是否未在 java 中检查 RadioButtons
- linux - 为什么命令行不能显示英文单词soundmark?
- javascript - 如何为多个上传按钮创建预览
- javascript - 在 Vuejs 中使用逗号作为分隔符将输入分隔为芯片