How can I get the sum of the first 5 rows?

How can I get the sum of the first 5 rows?

heizlerheizler Posts: 3Questions: 1Answers: 0

I have an example of how to sum a column of data on a page as well as the grand total but I need to get the total of the top 5 records, then the first 10 records and then the first 20. Can you point me in the right direction?

https://live.datatables.net/cisixiyi/1/edit

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,734Questions: 26Answers: 5,031
    edited March 5 Answer ✓

    Use column().data() to get the array of data in the column. Use toArray() to convert the returned API to a Javascript array. See the updated test case:
    https://live.datatables.net/cisixiyi/2/edit

    The test case shows using Javascript slice() to get the first 5 elements of the array. You can then sum this array.

    Another option si to iterate the array and in the loop have accumulators for 5, 10 and 20 records. Use the index to determine which accumulators to sum, for example:

    var data = table.column(4).data().toArray();
    
    var five = 0;
    var ten = 0;
    
    for (i=0; i<data.slice(0, 19).length; i++) {
      var value = data[i];
      if (i < 5) {
        five += value;
      }
      
      if (i < 10) {
        ten += value;
      }
      
    }
    

    Or choose any method that fits your specific situation.

    Kevin

  • heizlerheizler Posts: 3Questions: 1Answers: 0

    Perfect! Thanks for the help!

Sign In or Register to comment.