Sum value based on another column value
Sum value based on another column value
ucin
Posts: 13Questions: 4Answers: 0
in DataTables
Hello all,
I have a table which includes below columns (total column is 18) just listing the needed parts
DayName | val
Monday 30
Monday 10
Tuesday 25
Tuesday 40
Thursday 10
Thursday 15
I'm trying to get the sum for each day listed .So expected would be
Monday 40
Tuesday 65
Thursday 25
I tried below approach but not getting anything
var sum = dataTable
.cells( function ( index, data, node ) {
return dataTable.row( index ).data()[0] === 'Monday' ?
true : false;
}, 1)
.data()
.sum();
Can someone please give me a hint ?
This question has an accepted answers - jump to answer
Answers
Btw, I am able to get filtered columns to display as per day ;
but this method only returns a single column
I would look at using
rows().every()
to loop through all the rows. Using a Javascript object keep track of the sums by day, so you object would look something like this:This isn't complete but should give you an idea:
You will need to add the code to instantiate the sums object, etc. This assumes the weekday is in column 0 and the value to sum is in column 1.
Kevin
hi Kevin, thanks for your input. I'm somewhat confused, currently I can loop over the data via
I can filter by column number ;
but I'm not able to somehow combine both into a single function . I'm not trying to re-draw() , just need this value to save and send somewhere else.
so your first comment didn't help as , my initial problems was not being able to sum the values per dayName but you suggested I create an object with the sum of individual day, which is what i've been tiring to accomplish. Sorry if I misunderstood your approach !
Regards,
Ucin
Here is an example of what I meant:
http://live.datatables.net/nuqizujo/1/edit
Kevin
Thank you Kevin, much appreciated!