Using JavaScript for loops to return an empty array

When comparing the arrays in bakeryA and bakeryB with the ingredients of each recipe, the chooseRecipe function should print the name of the recipe if both bakeries have an ingredient for it. In this scenario, the output should be Persian Cheesecake. However, the function currently returns an empty array.

Even though I'm initializing suitableRecipe as an empty array, shouldn't suitableRecipe.push(recipes[i].name); take care of that?

I would appreciate any suggestions or guidance on a more efficient approach to solving this problem.

let bakeryA = ['saffron', 'eggs', 'tomato paste', 'coconut', 'custard'];
let bakeryB = ['milk', 'butter', 'cream cheese'];
let recipes = [
    {
        name: 'Coconut Sponge Cake',
        ingredients: ['coconut', 'cake base']
    },
    {
        name: 'Persian Cheesecake',
        ingredients: ['saffron', 'cream cheese']
    },
    {
        name: 'Custard Surprise',
        ingredients: ['custard', 'ground beef']
    }
];

const chooseRecipe = function(bakeryA, bakeryB, recipes) {
  let suitableRecipe = [];
  for (let i = 0; i < recipes.length; i++) {
    for (let j = 0; j < recipes[i].ingredients.length; j++) {
      for (let k = 0; k < bakeryA.length; k++) {
        if (bakeryA[k] === recipes[i].ingredients[j]) {
          for (let l = 0; l < bakeryB.length; l++) {
            for (let m = 0; m < recipes[i].ingredients; m++) {
              if (bakeryB[l] === recipes[i].ingredients[m]) {
                suitableRecipe.push(recipes[i].name);
              }
            }
          }
        }
      }
    }
  }
  return suitableRecipe;
}

console.log(chooseRecipe(bakeryA, bakeryB, recipes));

Answer №1

If you want a cleaner solution, consider utilizing Sets. Assuming that each ingredient is listed once in both bakeryA and bakeryB:

let bakeryA = ['saffron', 'eggs', 'tomato paste', 'coconut', 'custard'];
let bakeryB = ['milk', 'butter', 'cream cheese'];
let recipes = [
    {
        name: 'Coconut Sponge Cake',
        ingredients: ['coconut', 'cake base']
    },
    {
        name: 'Persian Cheesecake',
        ingredients: ['saffron', 'cream cheese']
    },
    {
        name: 'Custard Surprise',
        ingredients: ['custard', 'ground beef']
    }
];

const chooseRecipe = function(bakeryA, bakeryB, recipes) {
  let aIngredients = new Set(bakeryA);
  let bIngredients = new Set(bakeryB);
  return recipes.filter(recipe => 
     recipe.ingredients.every(ingredient =>
         aIngredients.has(ingredient) || bIngredients.has(ingredient))
  );
}

console.log(chooseRecipe(bakeryA, bakeryB, recipes));

Keep in mind:

This method is more efficient as it reduces redundant looping, which becomes crucial with larger data sets like bakeryA, bakeryB, ingredients, and recipes.

Answer №2

One suggestion is to leverage handy array methods such as filter, find, and some when tackling this type of scenario. In case you're wondering why your code isn't functioning, there's a quick solution available.

The issue lies in the absence of .length in your innermost for loop. The corrected loop should be:

for (let m = 0; m < recipes[i].ingredients.length; m++) {
...
}

You can make it more concise by utilizing the existing array features. An optimized solution could resemble this:

const select = (arrA, arrB, recipes) => recipes.filter(
    ({ingredients}) => arrA.some(i => ingredients.includes(i)) && arrB.some(i => ingredients.includes(i))
);

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

Cleaning up checkbox names by removing unnecessary characters

I'm having an issue with unnecessary characters in the names of checkboxes. There is a certain line var string = "<div class="blblb"><input type="checkbox" name="dasdasads"><input type="checbox" name="adsdsada"></div>"; The ...

Get names with specific characteristics by using a Javascript object that acts as an associative array

Can someone help me with my code? I'm trying to create an input box that, when I type in "A", will display the names of students who have earned "A" grades. I feel like I'm close to getting it right, but there's something missing. Any assist ...

Issues with jQuery focus function in Internet Explorer 11

Is there a way to set the focus on an anchor tag using the URL? Anchor Tag: <a id='714895'>&nbsp;</a> URL: jQuery Code: try { if(document.URL.indexOf("?ShowAllComments=True#") >= 0){ var elementClicked = "#" +location.hre ...

Deleting a row from the table with a single click on the X icon

Is there a way to delete individual rows in a table by clicking on a close icon instead of removing all rows at once? Additionally, I am looking for a better method to display rows in a table. You can view my current implementation here: link -> jsfiddl ...

Accessing Jquery's $.get function is currently not possible

I am experiencing difficulty fetching the contents of a json.txt file located in the same directory as this markup. Additionally, there are no errors appearing in Firebug. <!DOCTYPE html> <html> <head> <script type="text/ja ...

AngularJS Expandable Table - Unlocking Limitless Possibilities

Take a look at the code snippet below: <tbody> <tr ng-repeat-start="ticket in tickets"> <td> <button ng-if="ticket.expanded" ng-click="ticket.expanded = false">-</button> <button ng-if="!t ...

Switch out the view div element with ui-router

Currently, I am utilizing Angular ui-router to manage various views in the following manner: <div ui-view="header"></div> <div ui-view="nav"></div> <div ui-view></div> Upon Angular loading, the divs are automatically p ...

Is it possible for Vue.js to allow for templateUrl configuration similar to Angular.js?

Vue.js is great for its simplicity, but I want to avoid complicating it with browserify or webpack. I would rather use something similar to templateUrl in Angular, allowing me to serve partial pages (usually components) directly with Nginx. How can I ach ...

Comparing Redux Presentation Components with Container Components

As someone new to React development with Redux, I find myself intrigued by the concepts of Presentational Components and Container Components. How can components be classified as either Presentational or Container? What distinguishes one from the other ...

What is the best way to dynamically duplicate the Bootstrap multi-select feature?

$(function() { $('#days').multiselect({ includeSelectAllOption: true }); $('#btnSelected').click(function() { var selected = $("#days option:selected"); var message = ""; selected.each(function() { message ...

Node.js and Mongoose not functioning properly in collaboration

Searching for a user based on matching first and last names. router.post('/post/user/search/tag', function (req, res) { function getRegex(_query) { return { $regex: '^' + _query + '|.*' + _query, $optio ...

What is the best way to integrate external JavaScript libraries into Meteor.js?

When working with Meteor, how can I incorporate a 3rd party JavaScript library like gridster.js (http://gridster.net/)? Typically, I would include the script directly in the HTML page. However, is there a way to require it directly in the JavaScript file, ...

Instructions on how to extract information from a JSON response in SharePoint in order to display a list of

This is my first time working with JSON, so please be kind and patient with me :) I am currently working on a website, which can be found at http://msdn.microsoft.com/en-us/library/jj164022(v=office.15).aspx Here is a sample of the JavaScript code I am u ...

Twilio SMS Notification: The Class extension value provided is not a valid constructor or null

When attempting to utilize Twilio for sending SMS messages in a Vue.js project, I encountered an error while accessing Tools -> Developer Tools. <template> <div> <input type="text" v-model="to" placeholder="Ph ...

Delete a specific element from an array using a specified criteria

I'm attempting to remove a specific item from an array based on the selected option. To better understand, take a look at this code: component.html <fnd-extended-select label="Tipo Prodotto:" [(ngModel)]="landingType" name="tipoprodotto"> ...

Disregard validation of the view if the element includes the attributes `display: none`

Displayed below is an HTML text input that is designed to toggle visibility using jQuery's slideUp and slideDown functions, which change the display attribute to none with animation. My current challenge is that I do not want to validate the element w ...

In AngularJS, the execution of a subsequent AJAX call is reliant on the response of a preceding AJAX

Initially, I invoked the userSignupSubmit function. Within this method, another method called mobilenocheckingmethod is called. This method depends on the response from an AJAX call to make another AJAX call, but unfortunately, the second call does not w ...

Tips for accurately determining the byte count of text within a TextArea

I am trying to figure out how to accurately calculate the byte size of text within a specific textarea. Although I have access to .Net libraries, I am looking for a Javascript solution instead. How many bytes does each character represent? What is the most ...

Error message in Leaflet JS: Unable to access property 'addLayer' because it is undefined when trying to display drawnItems on the Map

My attempt to showcase a Leaflet Map with polygon-shaped surfaces encountered an issue. Sometimes, I face the error "cannot read property 'addLayer' of undefined," but when the page is refreshed, the map renders correctly. I am unsure where I wen ...

Weird behavior observed in PHP associative arrays

I've been working on creating an associative array in PHP recently. The goal is to have the "item Id" serve as the array key and the total spend on that item Id act as the value. To achieve this, I wrote a code snippet that pulls data from two separ ...