let say I have two arrays of typed object (same type), and I want to merge them, checking if an object already exists, then sum the old and new amount and return a new array with updated values
model:
class Ingredient {
constructor(public name: string, public amount: number){ }
}
arrays:
private ingredients: Ingredient[] = [
new Ingredient('farina', 500),
new Ingredient('burro', 80),
new Ingredient('uccellini', 5)
];
private newIngredients: Ingredient[] = [
new Ingredient('uova', 5),
new Ingredient('pancetta', 80),
new Ingredient('uccellini', 8)
];
when I try to create a method to check and merge arrays, I have an ERROR logged before to start writing my code!:
addIngredients(newIngredients: Ingredient[]) {
this.ingredients
.concat(this.newIngredients)
.reduce((result, curr) => {
});
}
This is the error:
error TS2345: Argument of type '(result: Ingredient, curr: Ingredient) =>
void' is not assignable to parameter of type
'(previousValue: Ingredient, currentValue: Ingredient, currentIndex: number, array: Ingredient[]) ...'.
Type 'void' is not assignable to type 'Ingredient'.
I cannot move on, please help me!
Ingredientinside the function passed toreduce. Same type asresult. Also ask yourself why you are reducing the array there? It seems highly unlikely that a method with the intention of adding something to an array would also reduce it to a single element.private ingredients: Ingredient[]withprivate ingredients: anyreturn resultis provided. Do you think I'm in a wrong way to do the job? I want an array with the matching elements are reduced by the amount