-2

new to ng4/typescript and having some difficulty. How do I sum the items in an array?

Addedenter image description here screenshot of what it looks like in action for example

        for (let card of this.cards) {
              for (let val of card.cards){
                if(val.value == "JACK"){
                  val.value = 10;
                }
                if (val.value == "QUEEN"){
                  val.value = 10;
                }
                if (val.value == "KING"){
                  val.value = 10;
                }
                if (val.value == "ACE"){
                  val.value = 10;
                }

                this.hand = Number(val.value) + Number(val.value); (I'm sure this is wrong)

             }
          }
malifa
  • 8,025
  • 2
  • 42
  • 57
Chris Simmons
  • 249
  • 2
  • 7
  • 19
  • 1
    Start by a simpler task. Try summing the elements of the following array: [1, 2, 3, 4]. – JB Nizet Nov 04 '17 at 17:09
  • Possible duplicate of [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – edkeveked Nov 04 '17 at 17:15

2 Answers2

10

Use Array#Reduce:

// Array of numbers
var array = [1,2,3,4,5];
var sum = array.reduce((acc, cur) => acc + cur, 0);
console.log(sum)

// Array of strings
var toNumber = ['1','2','3','4','5'];
var sumNumber = toNumber.reduce((acc, cur) => acc + Number(cur), 0)
console.log(sumNumber);
Marko Savic
  • 2,159
  • 2
  • 14
  • 27
1
let sum = array.reduce(function (acc, cur) { return acc + cur; });
Danilo
  • 631
  • 1
  • 9
  • 24
  • Whilst this answer may be correct, some explanation of why and how would go a long way. – Smokey Dawson Nov 04 '19 at 01:56
  • the array.reduce((acc, cur) => acc + cur, 0); not work on AnularJS old versions, this that i have wrote works for all versions – Danilo Nov 04 '19 at 09:17