Finding compatibility between two arrays with flexibility

I am currently working on an Ionic app that involves an array of ingredients and a service with recipes. You can find the structure of the recipe service here.

My goal is to match the ingredients with the recipes. Currently, I have implemented the following logic:

 
 this.truelist = [...this.spliterStrIngredients()]; // an array of 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);
}

While this method works when selecting the exact recipe, I am looking to make it more flexible. For instance, I would like to be able to match an array of ingredients like pasta+cheese+carrots with a recipe like carbonara.

Any help or suggestions on how to achieve this flexibility would be greatly appreciated.

Answer №1

Based on the guidelines provided, here is a tailored solution that meets your requirements:

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 discoverMatchingRecipe(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);
}

discoverMatchingRecipe(myIngredientsA); // No match found as 'Egg' is missing
discoverMatchingRecipe(myIngredientsB); // Match found as all ingredients match
discoverMatchingRecipe(myIngredientsC); // Match found as all ingredients match, regardless of extras

Answer №2

Appreciate the solution, however, there seems to be an issue when the menu is set as [carrot, pasta, cheese]. It consistently returns false. I would prefer a solution that can work with items in any arrangement.

Answer №3

Having gone through your explanation, I devised a solution that suits my understanding. Since I lack knowledge in typescript, I opted to write the code in pure JavaScript:

const spaghetti = ['noodles', 'sauce'];
const dishA = ['noodles', 'sauce', 'vegetables'];
const dishB = ['noodles', 'tomato'];
const dishC = ['vegetables', 'noodles', 'sauce'];

const checkIngredients = (dish1, dish2) => {
  for (let i = 0; i < dish1.length; i++) {
    if (!dish2.includes(dish1[i])) {
        return false;
    }
  }
  return true;
};

console.log(checkIngredients(spaghetti, dishA)); // true: dishA has all the ingredients in Spaghetti plus vegetables
console.log(checkIngredients(spaghetti, dishB)); // false: dishB lacks sauce
console.log(checkIngredients(spaghetti, dishC)); // true: the order of ingredients doesn't matter

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My goal is to utilize React JS to generate a table by sending the values through props using an array of objects

I have experience building tables as part of various projects, but I am facing challenges creating a table based on the provided format for this specific project. My goal is to utilize the RecordTable Component, render the table component, pass the row com ...

What could be causing the JSON.parse() function to fail in my program?

Currently utilizing Django and attempting to fetch data directly using javascript. Below are the code snippets. Within the idx_map.html, the JS section appears as follows: var act = '{{ activities_json }}'; document.getElementById("json") ...

Iterate through an array containing objects that may have optional properties, ensuring to loop through the entire

I need help iterating through an array of objects with a specific interface structure: export interface Incident { ID: string; userName1?: string; userName2?: string; userPhoneNumber?: string; crashSeverity: number; crashTime: number; } Here ...

Interacting with an element within a jQuery dialog box created through a function click

I'm encountering an unusual issue with jQuery and Javascript across all browsers (IE, FF, Chrome). On my (asp.net) webpage, I have the following structure: A header with numerous dynamically generated buttons at PreRender A hidden div containing but ...

Can webpack integrate React components from a package and then recompile the package?

I am currently in the process of creating an npm package to standardize my layout components that are based on geist components. Initially, I attempted to use the npm package as a local component, but encountered a webpack loader error when trying to read ...

Limiting the style of an input element

How can I mask the input field within an <input type="text" /> tag to restrict the user to a specific format of [].[], with any number of characters allowed between the brackets? For example: "[Analysis].[Analysis]" or another instance: "[Analysi ...

What is the best way to remove any objects in this array that have empty strings as values?

I have been developing a form using Angular 14. The form consists of a primary section, which includes the user's necessary information, and a secondary section where users can input additional data (an array of residences displayed in a table) befor ...

Preventing Flash of Unstyled Content in ElectronJS Browser Windows

Upon creating a new BrowserWindow and utilizing loadURL to incorporate an html file within the renderer, there is a brief instance where unstyled content is displayed for approximately half a second before the css is loaded. window.loadURL('file://&a ...

Cannot trigger a click event on nginclude in AngularJS

I have a question regarding including a new page using the nginclude directive. The click event defined in the included page is not working properly. Main Application: <div ng-app=""> <input type="text" ng-model="ss"/> <div ...

Developing an Angular Chart with AJAX

Utilizing the power of angular-chart.js, I have successfully generated a chart with the provided code snippet. However, my goal is to dynamically generate a chart using AJAX calls. Unfortunately, when I attempt to load the chart through AJAX, it fails to r ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

Is there a way to create a comprehensive list of all the possible winning combinations in a game of 4-Dimensional Connect Four?

Currently, I am developing a 4D Connect Four game using Javascript. The game can be accessed here. My next goal is to incorporate win-checking functionality. To simplify the process and save time, my plan is to pre-create a comprehensive list of all poten ...

Type children are not permitted in the TypeScript container

Container is a component that extends from @material-ui/core and does not accept children of type React.ReactNode. Layout.tsx: import { Container } from "@material-ui/core"; type LayoutProps = { children: React.ReactNode; }; function Layout( ...

Unable to implement the `omega/theme.css` file within the angular.json configuration

"styles": [ "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css", "node_modules/primeicons/primeicons.css", ...

Adding a unique value to an array using JQuery when it does not already exist

In need of assistance with a function that is supposed to add values to an array if they do not already exist. var category_json = new Array(); $.ajax({ type: 'POST', url: "<?php ech ...

Angular 2 - mistakenly spelled component name in selector tag leading to error notifications

As a newcomer to Angular2, I am uncertain about the most suitable term to use when referring to a selector/component tag. An instance of what I'm calling a selector/component tag is the app-menu tag showcased in the HTML sample below. In case any miss ...

Send information using AJAX within a .NET integrated browser

In our current setup, we utilize a .NET embedded browser to showcase an HTML page that is generated by applying an XSLT file to an XML file using .NET. This process results in HTML content displayed within the embedded browser through the DocumentText prop ...

Guide to setting up an object array in JavaScript with unique child elements and no duplicate values

I have an array that looks like this: sampleArray = ["x", "y", "z". "a.b", "a.b.c", "a.b.d", "a.e.f", "a.e.g"] However, I am aiming to transform it into the following structure, or something similar to it: newArray: [ { "x": [] }, ...

A URL that quickly updates live content from a backend script

As a beginner, I am seeking guidance as to where to start on my journey of learning. I need assistance in creating a script that can efficiently fit within a small URI space and constantly updates itself with information from a server script. My target bro ...

"Implementing Two-Way SSL with Angular 2 and BrowserSync

Currently, I am working on an Angular2 application that requires two-way SSL authentication. This means that the browser needs to present a valid (PFX) certificate in order to access the application. For deployment, I am using lite-server (which utilizes B ...