-1

I have an array like below.

[{"rowid":1,"amount":5000,"checked":true},
{"rowid":2,"amount":1500,"checked":true},
{"rowid":3,"amount":500,"checked":true}]

where I have 3 rows and in each row I have a field called amount. I want to add the value of all amount fields so that I will get result 7000.

ananya
  • 1,001
  • 6
  • 33
  • 50
  • TypeScript is just JavaScript with type annotations. It offers no new features to handle a problem like this. By the way, this is not a "Jsonarray", It's an "array". With regard to your problem itself, is there some problem with the approach of looping over the array elements and adding up the `amount` property of each one? –  Jun 12 '17 at 08:51
  • Possible duplicate of [Better way to sum a property value in an array (Using Angularjs)](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array-using-angularjs) –  Jun 12 '17 at 08:55
  • @ torazaburo .I donot know javascript also. and i want the solution using typescript – ananya Jun 12 '17 at 09:09
  • @ torazaburo Yes i want the same functionality like this. https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array-using-angularjs. Can you please tell me how to acheive the same using Typescript. – ananya Jun 12 '17 at 09:12

1 Answers1

1

To extract amount use .map and to add items .reduce

let arraylist = [{"rowid":1,"amount":5000,"checked":true}
                 {"rowid":2,"amount":1500,"checked":true},
                 {"rowid":3,"amount":500,"checked":true}];
const bArray = arraylist.map(({ amount }) => amount);
const result = bArray.reduce(function(a, b) { return a + b; }, 0);
console.log(result);     // output = 7000
Cling
  • 489
  • 1
  • 6
  • 15