-3

My array:

const a = [                                       
  {                                               
    "baseFare": "1439.00",                                       
  },  
  {                                               
    "baseFare": "1739.00",                                       
  },    
  {                                               
    "baseFare": "1039.00",                                       
  },                                    
]                                             

Note: The number of values in const a will increase or decrease its user decisions ! there may be one or 5 or 7 values in the array !

How to sum all the values and output a single value , and in somecase if its only one value then the out put should be direct single value !

How to achive this ?

My code :

a.reduce((a, b) => a + b, 0)

hellodevs
  • 27
  • 5

2 Answers2

1

you are almost there try this,

a.reduce((a, b) => a + (+b.baseFare), 0);

//a is the accumulator , and it start with 0 its an integer
//If you need to access baseFare, then you have to get it from object b.baseFare,
//b.baseFare is a string so you have to convert it to a number (+b.baseFare) is for that

if you really need to get it as a floating point number, for ex: 5000, showing as "5000.00" then try this out

let sum = a.reduce((a, b) => a + (+b.baseFare), 0);;
sum = sum.toFixed(2); //"4217.00"
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
1

Just loop, converting the strings to numbers as you go:

let result = 0;
for (const entry of a) {
    result += +entry.baseFare;
}

Or with destructuring:

let result = 0;
for (const {baseFare} of a) {
//         ^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−− destructuring
    result += +baseFare;
}

That unary + is just one way to convert from string to number. I go into all your options in this other answer.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875