1

i'm having an array of string with in currency format for each array value:

var sells = ['INR1,433,200.00','INR5,750.00','INR12,000.00','INR1,905.00','INR235.00'];

i try to loop through each value of this array , and sum it to get the total in currency format

var total = 0;
sells.forEach(function(sell) {
    total += sell;
});
console.log(total);

When i see the browser console log the result is always NaN , i expected the result to be INR1,453,090.00

jojo
  • 126
  • 11

1 Answers1

2

You replace INR and the commas and cast the String into a Number:

var sells = ['INR1,433,200.00','INR5,750.00','INR12,000.00','INR1,905.00','INR235.00'];

var total = 0;
sells.forEach(function(sell) {
    total += +sell.replace('INR','').replace(/,/g,'');
});
console.log(total);

You can also use reduce:

var sells = ['INR1,433,200.00', 'INR5,750.00', 'INR12,000.00', 'INR1,905.00', 'INR235.00'];
console.log(sells.reduce((acc, val) => acc + +val.replace('INR', '').replace(/,/g, ''), 0));
shrys
  • 5,860
  • 2
  • 21
  • 36