3

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!

6
  • 2
    You should return an Ingredient inside the function passed to reduce. Same type as result. 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. Commented Mar 30, 2018 at 23:04
  • try to replace private ingredients: Ingredient[] with private ingredients: any Commented Mar 30, 2018 at 23:04
  • 2
    reduce returns "void" when it has no inner code block hence the error, i would suggest also setting a default value for the accumulator of the reduce function which is the second argument. I.E array#reduce((a,c) => a+c, 0) where 0 is the default value for accumulator Commented Mar 30, 2018 at 23:06
  • @BalázsÉdes thanks, the error disappeared when return result is 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 Commented Mar 30, 2018 at 23:12
  • 2
    @ufollettu Read the docs and examples on Array.prototype.reduce, I think you expect it to do something else Commented Mar 31, 2018 at 12:58

1 Answer 1

8

In your .reduce method, return result and the error will disappear.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.