0

How can I add all the mybag array values into total_w where mybag has mixed values of float or int?

  var mybag = []; 
  mybag[0] = 20.50; 
  mybag[1] = 10.13;
  mybag[3] = 0;

  //so total_w should be 30.63  not: 20.5010.13

  var total_w = 0;
  var comma = '';
  for (key in mybag) {
    active_mybag = active_mybag + comma + parseFloat(mybag[key]).toFixed(2);
    total_w = Math.round(total_w + parseFloat(mybag[key]).toFixed(2));
    comma = ",";    
  }

  console.log('> ', total_w, active_mybag);
weston
  • 54,145
  • 21
  • 145
  • 203

2 Answers2

1

There are a number of problems with your code, so rather than a string of comments here's an answer.

var mybag = [ /* bunch of values */];
var total = +mybag.reduce((a, b) => a + +b, 0).toFixed(2);

Will work with numbers or numeric strings. Fiddle. Here's a break down:

the reduce starts with 0.

the 'a' parameter is the accumulator.

the 'b' parameter is the array value for that iteration.

b is converted to a number by the unary plus operator

b is added to a and returned

the total sum is reduced to a numeric string of 2-digit precision

which is converted back to a number by the plus at the front

Jared Smith
  • 19,721
  • 5
  • 45
  • 83
  • 1
    That's great, but the comments are necessary for them to actually learn anything. – 4castle May 19 '16 at 00:37
  • It's not a "coercion" but "conversion" – zerkms May 19 '16 at 00:38
  • @4castle was in the process of writing the explanation :) – Jared Smith May 19 '16 at 00:40
  • http://paste.ubuntu.com/16502176/ - this is also working. I am not getting your second line, can you show with a working example as per question. –  May 19 '16 at 00:42
  • I wasn't talking about explaining *your* code, I meant you need to explain what was wrong with *their* code so that they can solve their future questions too. – 4castle May 19 '16 at 00:43
  • 1
    @YumYumYum no, my code works just fine: https://jsfiddle.net/cke2swmt/ all I changed was translating the es6 arrow function to the regular function syntax. – Jared Smith May 19 '16 at 10:08
0
  var active_mybag = [];  

  var total_w = mybag.reduce(function(acc,e){

    // Value of array to float
    e = parseFloat(e);

    // Collect text representations of rounded value
    active_mybag.push( e.toFixed(2) );

    // Subtotal
    return acc + e;

  },0 ).toFixed(2); // Convert sum to string representation

  active_mybag = active_mybag.join(',');

[ https://jsfiddle.net/ot1p37mv/ ]

stdob--
  • 28,222
  • 5
  • 58
  • 73