首页 > 解决方案 > 灵活匹配两个阵列

问题描述

我在一个应用程序 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。

谢谢您的帮助

标签: javascriptangulartypescriptionic-frameworktypes

解决方案


按照您提出的规则,这里有一个适合您需求的解决方案:

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

推荐阅读