I've been working on this and here is what I have tried so far:
groceryList = [];
ngOnInit() {
this._recipesSub = this.recipesService.recipes.subscribe((receivedData) => {
this.loadedRecipes = receivedData.recipes;
});
}
onCheckRecipe(e) {
if (e.detail.checked === true) {
let tickedRecipe = e.detail.value;
let selectedRecipeIngredients;
for (let recipe of this.loadedRecipes) {
if (recipe.name === tickedRecipe) {
selectedRecipeIngredients = recipe.ingredients;
}
}
for (let selectedIng of selectedRecipeIngredients) {
for (let existingIng of this.groceryList) {
if (selectedIng.name) {
this.groceryList.push(selectedIng);
}
}
}
console.log(this.groceryList);
}
}
When I check the console, I see the following output:
(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {_id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g"}
1: {_id: "5f64ac1eb227fea1f63a5c9a", name: "cherries", quantity: "15g"}
2: {_id: "5f64ac1eb227fea1f63a5c9b", name: "honey", quantity: "30g"}
3: {_id: "5f64ac1eb227fea1f63a5c9c", name: "almond flour", quantity: "10g"}
4: {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"}
5: {_id: "5f64ac1eb227fea1f63a5c9f", name: "egg", quantity: "10g"}
6: {_id: "5f64ac1eb227fea1f63a5ca0", name: "unsalted butter", quantity: "30g"}
7: {_id: "5f64ac1eb227fea1f63a5ca1", name: "peanut butter", quantity: "50g"}
length: 8
__proto__: Array(0)
My goal is to avoid having name: "almond flour"
appear twice in the array. Instead, I want to combine the quantities like this:
{_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "20g"}
The desired functionality is to add each ingredient to the groceryList
only if it's not already present. If an ingredient is already in the list, then just update its quantity.
I'm unsure about the approach to take to achieve this. Any suggestions or ideas would be greatly appreciated.
** Also the remove option
onCheckRecipe(e) {
if (e.detail.checked === true) {
for (let recipe of this.loadedRecipes) {
if (recipe.name === e.detail.value) {
recipe.ingredients.forEach((eachIngredient) => {
let matchedIng = this.groceryList.find(function (foundIng) {
return foundIng.name === eachIngredient.name;
});
if (matchedIng) {
matchedIng.quantity =
matchedIng.quantity + eachIngredient.quantity;
} else {
this.groceryList.push(eachIngredient);
}
});
}
}
} else {
for (let recipe of this.loadedRecipes) {
if (recipe.name === e.detail.value) {
recipe.ingredients.forEach((element) => {
let matched = this.groceryList.find(function (foundIngre) {
return foundIngre.name === element.name;
});
if (matched.quantity === element.quantity) {
let index = this.groceryList.findIndex(
(x) => x.name === matched.name
);
this.groceryList.splice(index, 1);
} else {
matched.quantity = matched.quantity - element.quantity;
}
});
}
}
}
}