Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 269
Mayur Avatar asked Apr 02 '19 06:04

Mayur


People also ask

How do you sum values in Lodash?

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.

What is The Lodash Sumby method?

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.

Why do I need to use Lodash for arrays?

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.

How to find the sum of the values in an array?

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.


1 Answers

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>
like image 153
31piy Avatar answered Oct 03 '22 04:10

31piy