¿Cómo filtro tal matriz?
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" ], }, ]basado en elementos en dicha matriz
const selectedIngredients = ["milk", "salt"]Jugué con una combinación de array.filter, array.some como se muestra en Comprobar si una matriz contiene algún elemento de otra matriz en JavaScript pero no puedo hacer que funcione correctamente
Quiero obtener recetas con id 2 y 3 como resultado
Puede establecer la condición del filter para que los ingredientes selectedIngredients incluyan un elemento que esté incluido en la propiedad de ingredients del elemento:
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"]}]; const selectedIngredients = ["milk", "salt"] const result = !selectedIngredients.length ? [...recipes] : recipes.filter(e => selectedIngredients.some(f => e.ingredients.includes(f))) console.log(result) 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" ], }, ] const selectedIngredients = ["flour", "water"] const selectAny = (list, filter) => list.filter(e => e.ingredients.some(i => filter.includes(i))); const selectAll = (list, filter) => list.filter(e => filter.every(i => e.ingredients.includes(i))); console.log('any', selectAny(recipes, selectedIngredients)); console.log('all', selectAll(recipes, selectedIngredients));yo lo haría así
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'], }, ]; // const doRebuild = (selectedIngredients)=>{ const build = []; for(const two of selectedIngredients){ for(const one of recipes){ if(one.ingredients.some((a)=>two === a))build.push(one); } } return build.length > 0 ? build : ['No recipes']; }; // const content1 = doRebuild(['milk2', 'salt2']); const content2 = doRebuild(['milk', 'salt']); console.log(content1); console.log(content2);