[英]return object if his property matches all the items inside an array (ex ingredients for recipes)
I'm learning js and I was trying to filter recipes based on the ingredients I have inside an array but the check done with Array.every() seems to not work, what am I doing wrong?我正在学习 js,我试图根据我在数组中的成分过滤食谱,但是用 Array.every() 完成的检查似乎不起作用,我做错了什么? Here's the code, thanks all!
这是代码,谢谢大家!
const plates = [
{
name: "carbonara",
ingredients: ["eggs", "milk", "pepper", "pasta", "cheese"],
time: 30,
difficulty: "easy",
},
{
name: "oil_pepper",
ingredients: ["oil", "pepper", "pasta", "garlic"],
time: 20,
difficulty: "medium",
},
{
name: "tomato",
ingredients: ["pasta", "tomato", "garlic", "onion"],
time: "30",
difficulty: "hard",
},
];
const fridge = ["oil", "pepper", "pasta", "garlic"];
let filteredPlates = [];
const filter = () => {
plates.forEach((element) =>
fridge.forEach((element2) => {
if (
element.ingredients.every((element3) =>
element3.includes(element2.toString())
)
) {
filteredPlates.push(element);
return filteredPlates;
}
})
);
};
filter();
console.log(filteredPlates);
You are over-complicating the problem.你把问题复杂化了。 You just need to check for each plate, whether every ingredient in that plate's recipe is included in the fridge.
您只需要检查每个盘子,该盘子食谱中的每种成分是否都包含在冰箱中。 You can use
Array.filter
for this purpose:您可以为此目的使用
Array.filter
:
const plates = [ { name: "carbonara", ingredients: ["eggs", "milk", "pepper", "pasta", "cheese"], time: 30, difficulty: "easy", }, { name: "oil_pepper", ingredients: ["oil", "pepper", "pasta", "garlic"], time: 20, difficulty: "medium", }, { name: "tomato", ingredients: ["pasta", "tomato", "garlic", "onion"], time: "30", difficulty: "hard", }, ]; const fridge = ["oil", "pepper", "pasta", "garlic"]; const filteredPlates = plates.filter(plt => plt.ingredients.every(ing => fridge.includes(ing))) console.log(filteredPlates)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.