Searching for an array of objects containing nested arrays in JavaScript

I've been struggling with this function for two days and still can't get it right. I need the function to only return objects that meet all filter criteria in the array. The issue is that it should only return objects that satisfy every filter.

Here are my filters:

const myFiltersIngredients = ['flour', 'chicken']

And here are the objects in my array:

    const myRecipes = [
  {
    name: 'grandma's pie',
    ingredients: [
      {
        ingredient: 'flour',
        ingredientUnit: 'grams',
        ingredientQuantity: 500
      },
      {
        ingredient: 'chicken',
        ingredientUnit: 'grams',
        ingredientQuantity: 500
      }
    ]
  },
  {
    name: 'cookie',
    ingredients: [
      {
        ingredient: 'flour',
        ingredientUnit: 'grams',
        ingredientQuantity: 500
      },
      {
        ingredient: 'butter',
        ingredientUnit: 'grams',
        ingredientQuantity: 500
      }
    ]
  }
]

Answer №1

const myFiltersIngredients = ['rice', 'chicken'];

const myDishes = [{
        name: 'grandma's pie',
        ingredients: [{
                ingredient: 'rice',
                ingredientUnit: 'grams',
                ingredientQuantity: 500
            },
            {
                ingredient: 'chicken',
                ingredientUnit: 'grams',
                ingredientQuantity: 500
            }
        ]
    },
    {
        name: 'cookie',
        ingredients: [{
                ingredient: 'rice',
                ingredientUnit: 'grams',
                ingredientQuantity: 500
            },
            {
                ingredient: 'butter',
                ingredientUnit: 'grams',
                ingredientQuantity: 500
            }
        ]
    }
];

const mySelectedDishes = myDishes.filter(({
    ingredients
}) => myFiltersIngredients.every(myfilter => ingredients.map(({
    ingredient
}) => ingredient).includes(myfilter)));

console.log( mySelectedDishes );

Answer №2

Hopefully, this demonstration serves as a helpful guide in the right direction.

For further information, you can refer to the documentation of .filter and .every array methods.

To elaborate briefly:

The .filter method accepts a function as an argument and processes each object in the array based on the function's criteria, returning only those items that meet the specified conditions.

On the other hand, the .every method evaluates whether all elements in the array satisfy a specific condition passed through a function.

In my provided code snippet, I begin by filtering recipes based on ingredients and storing the filtered result in a variable. The function used for filtering checks if all ingredients associated with each recipe are present in the myFiltersIngredients array.

const myFiltersIngredients = ['flour', 'chicken'];

const myRecipes = [
  {
    name: 'Grandma\'s pie',
    ingredients: [
      {
        ingredient: 'flour',
        ingredientUnit: 'gram(s)',
        ingredientQuantity: 500
      },
      {
        ingredient: 'chicken',
        ingredientUnit: 'gram(s)',
        ingredientQuantity: 500
      }
    ]
  },
  {
    name: 'Cookie',
    ingredients: [
      {
        ingredient: 'flour',
        ingredientUnit: 'gram(s)',
        ingredientQuantity: 500
      },
      {
        ingredient: 'butter',
        ingredientUnit: 'gram(s)',
        ingredientQuantity: 500
      }
    ]
  }
];

const filteredRecipes = myRecipes.filter(o => {
  return o.ingredients.every(
    ({ingredient}) => myFiltersIngredients.includes(ingredient)
  );
});

console.log(filteredRecipes);

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

Conceal the Vue router on a webpage

How can I hide the vue-router from my login page? I want to remove the menu on the Login page. Is it possible and how would I achieve that? Here is the code for the Login page: Login <template> <div> <h1>Login</h1> ...

Can you explain the process of retrieving API information from a component directory with Next.js?

In the components folder, I have created a reusable component that displays user details for those who log into the system in the header section. Currently, I am attempting to utilize getInitialProps with isomorphic-unfetch. static async getInitialProps( ...

Create new instances of Backbone Models using an existing Backbone Model as a template

Within my app, I am planning to include a configuration file called config.json as a Backbone Model. Here is an example of how it will be loaded: var Config = Backbone.Model.extend({ defaults: { base: '' }, url: 'config. ...

Initialization of Angular provider $get is missing

Within my 'app.js' file, I have the following code that is used in my config to set up $navigationProvider.doSomething(). When running this code, Test1 and Test3 are alerted correctly, but I'm having trouble with getting my this.$get method ...

Newbie in Distress: Help Required Due to Server Error

Currently working on the contacts page for a website and I need the div element to disappear once an email is successfully sent. In order to hide a Div element using Javascript, I created the following function: function hideDiv(){ document.getElement ...

Associate information with HTML elements

I've come across this question multiple times, but the solutions are mostly focused on HTML5. My DOCTYPE declaration is: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> I'm looking t ...

Choose Selectize.js to auto-populate inputs

I am currently using selectize.js for my project: $("#abc").selectize({ valueField: 'name', labelField: 'name', searchField: ['name'], plugins: ['remove_button'], createOnBlur: true, ...

How does Code Sandbox, an online in-browser code editor, manage file storage within the browser?

What are the ways in which Code Sandbox and StackBlitz, as online in-browser code editors, store files within the browser? ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

display the designated image as a priority

I am designing a loading screen for my website that includes the loading of multiple images, scripts, and other elements. While the HTML and CSS part is working well, I need to ensure that the "loading..." image is loaded before anything else on the page. ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

Is there a discrepancy in the JSON algorithm?

While using google chrome, I encountered the following scenario: I had an object in javascript that looked like this: var b = { text: 'hello world, you "cool"' }; I then used JSON.stringify to convert it to a string and sent it to the dat ...

Access the input field value with PHP and store it in a variable

I previously looked into this issue, but the solution provided in the accepted answer did not resolve it for me: How to get input field value using PHP Below is an excerpt from my result.php file: ... <th> <form name="form" action= ...

Using Rails AJAX to dynamically load partials without the need to submit

Imagine creating a dynamic page layout with two interactive columns: | Design Your Pizza Form | Suggested Pizzas | As you customize your pizza using the form in the left column, the right column will start suggesting various types of pizzas based on your ...

The Jade template is not rendering the page correctly as anticipated

I'm working with Node.js & express, using the Jade template for the view. My issue is that the Test text is currently hidden under the black navigation bar. How can I move it to the bottom, below the navbar? What am I missing in my code? Here is the ...

Strategies for extracting special character codes from API data within a React functional component

I have been experimenting with a simple trivia API to improve my understanding of REACT. I have noticed that the question data is returning with special character codes, which is causing issues with react jsx. Can anyone suggest a method to easily convert ...

Mirror the input text to another input within a for loop

I have a list of questions displayed, each with an input field for entering a phone number. How can I use jQuery or JavaScript in a for-loop to mirror the text entered in the first phone input box to all subsequent phone input boxes? ..Enter your phone... ...

Being able to automatically update my JSON file without needing to manually refresh the webpage is a feature I am interested in exploring

I have a server that automatically updates a JSON file. However, the JavaScript code I have implemented below reads the JSON file and displays it to the client, but it always refreshes the page. I am looking for a solution on how to read my JSON file ever ...

How to use the importrange function to calculate the frequency of a specific value in a column

Within this google sheet, there is text data located in range O3:O: https://docs.google.com/spreadsheets/d/1xNFVHLnQGkRgZdLmejCyU0BByOPBY8NMoIYj6SkTFGY/edit?usp=sharing The main goal here is to use Query + importrange to calculate how many times the value ...

The process of transforming a string in JSON format into a JSONArray

Struggling with converting a String to a JSON Array: The String in question is arrayPersona = ""[{\"nombre\": \"Luis\", \"apellido\": \"cardozo\", \"edad\": 23}, {\"nombre\": \"Pedro&bsol ...