Home > Enterprise >  How to sum a values in an array using typescript
How to sum a values in an array using typescript

Time:03-23

I want to calculate the total value of the below array

 let Gender1 = [ Male1[22,34,76,24,30],
                    Male2[12,15,18,20],
                    Male3[16,18] ];

CodePudding user response:

Assuming you fix the formatting of your arrays, Use .flatMap and .reduce to flatten and then summarize.

let gender1 = [[22,34,76,24,30], [12,15,18,20], [16,18]]
let sum = gender1.flatMap(num => num).reduce((a, b) => a b)

This has nothing to do with Angular specifically.

CodePudding user response:

  • firstly need to flat your array via flat method
  • then via reduce method we can sum all number in the array

let Gender1 = [[22,34,76,24,30], [12,15,18,20], [16,18]];

const result = Gender1.flat().reduce((a, c) => a   c, 0);

console.log(result);

  • Related