Home:ALL Converter>Filter array with objects based on another array

Filter array with objects based on another array

Ask Time:2021-10-09T06:35:30         Author:sikor

Json Formatter

How do I filter such array:

const recipes = [
{
    "id": 1,
    "name": "Boiled Egg",
    "ingredients": [
        "egg",
        "water"
    ],
},
{
    "id": 2,
    "name": "Pancakes",
    "ingredients": [
        "egg",
        "milk",
        "flour"
    ],
},
{
    "id": 3,
    "name": "Bread",
    "ingredients": [
        "flour",
        "water",
        "salt"

    ],
},
]

based on elements in such array

const selectedIngredients = ["milk", "salt"]

I played with combination of array.filter, array.some as show in Check if an array contains any element of another array in JavaScript but can't get it working properly

I want to get recipes with id 2 and 3 as a result

Author:sikor,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69502338/filter-array-with-objects-based-on-another-array
Spectric :

You can set the condition of the filter to whether selectedIngredients includes an item that is included in the item's ingredients property:\n\r\n\r\nconst recipes=[{id:1,name:\"Boiled Egg\",ingredients:[\"egg\",\"water\"]},{id:2,name:\"Pancakes\",ingredients:[\"egg\",\"milk\",\"flour\"]},{id:3,name:\"Bread\",ingredients:[\"flour\",\"water\",\"salt\"]}];\n\nconst selectedIngredients = [\"milk\", \"salt\"]\n\nconst result = !selectedIngredients.length ? [...recipes] : recipes.filter(e => selectedIngredients.some(f => e.ingredients.includes(f)))\n\nconsole.log(result)",
2021-10-08T22:43:01
Christian Fritz :

\r\n\r\nconst recipes = [\n{\n \"id\": 1,\n \"name\": \"Boiled Egg\",\n \"ingredients\": [\n \"egg\",\n \"water\"\n ],\n},\n{\n \"id\": 2,\n \"name\": \"Pancakes\",\n \"ingredients\": [\n \"egg\",\n \"milk\",\n \"flour\"\n ],\n},\n{\n \"id\": 3,\n \"name\": \"Bread\",\n \"ingredients\": [\n \"flour\",\n \"water\",\n \"salt\"\n ],\n},\n]\n\nconst selectedIngredients = [\"flour\", \"water\"]\n\nconst selectAny = (list, filter) =>\n list.filter(e => e.ingredients.some(i => filter.includes(i)));\n\nconst selectAll = (list, filter) =>\n list.filter(e => filter.every(i => e.ingredients.includes(i)));\n\nconsole.log('any', selectAny(recipes, selectedIngredients));\nconsole.log('all', selectAll(recipes, selectedIngredients));",
2021-10-08T22:45:22
yy