Search code examples
javascriptjquerylodashangular7

How to sum string value in lodash by particular column?


Hi there i am using lodash for aggregation purpose but i have stuck at one place i am getting my value as a string instead of float so its concate rather then summing the value.

Below is the way tried.

var data = [{extendedPrice: "5151.059", month: "January"}, 
            {extendedPrice: "8921.0336", month: "March"},
            {extendedPrice: "2036.9865", month: "April"}];

var sumValue = _.sumBy(data,extendedPrice);

The result from above

5151.0598921.03362036.9865

Expected Result:

16109.0791

Any help would be really appreciated.


Solution

  • Since the values are strings, the + means concatenation, not addition. You can supply a callback to the _.sumBy function:

    _.sumBy(data, item => Number(item.extendedPrice));
    

    Working demo:

    var data = [{extendedPrice: "5151.059", month: "January"}, 
                {extendedPrice: "8921.0336", month: "March"},
                {extendedPrice: "2036.9865", month: "April"}];
    
    var sumValue = _.sumBy(data, item => Number(item.extendedPrice));
    console.log(sumValue);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>