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.
Lodash _.sum () Method. Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.sum () method is used to find the sum of the values in the array.
The Lodash sumBy method allows you to add the values of the objects in your array, specifying the objet property that should be targeted. In this article, you will learn about the Lodash sumBy method, and how it can be helpful in your website or application.
I need to use Lodash for this because I need good performance if these arrays get huge. Show activity on this post. This is a case of reduction for each unique element. I always use _.groupBy and then _.map the result to an array after applying the reduction.
The _.sum () method is used to find the sum of the values in the array. Parameters: This method accepts a single parameter as mentioned above and described below: array: This parameter holds the array to iterate over. Return Value: This method returns the sum of the values in the array.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With