Home > other >  return object if his property matches all the items inside an array (ex ingredients for recipes)
return object if his property matches all the items inside an array (ex ingredients for recipes)

Time:09-02

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? 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);

CodePudding user response:

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:

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)

  • Related