-2

So I have an array with differents objects and all of these objects contain a property called "amount". I want to add all these amount values together to display the total amount

I've tried using a for loop but where I say "this.totalItemCount = this.cart[i].amount;" but it will only give me the amount of that specific object.

(2) [{…}, {…}]
0: {movie: {…}, amount: 3}
1: {movie: {…}, amount: 3}
length: 2

loop

totalItemCount: number;

addMovie(movie: IMovie) {
    let foundMovie = false;

    for (let i = 0; i < this.cart.length; i++) {
      if (movie.id === this.cart[i].movie.id) {
        this.cart[i].amount++;
        foundMovie = true;
        this.totalItemCount = this.cart[i].amount;
        console.log(this.totalItemCount)
      }
    }

I expect my variable "totalItemCount" to display 6.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
piedude
  • 111
  • 1
  • 10

1 Answers1

1

Use reduce:

    const arr = [{ amount: 3 }, { amount: 3 }];
    const res = arr.reduce((acc, { amount }) => acc + amount, 0);
    console.log(res);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79