How to group multiple columns in jquery datatables

Jonathan John picture Jonathan John · Jul 1, 2015 · Viewed 11.6k times · Source

How to collapse and expand the table based on multiple columns grouping.

For example I have table like this

---------------------------------------------------------------
location   |   size   | cont_no |   price  |  depot  |  cond  |
---------------------------------------------------------------
   USA     |    XX    |   123   |    230   |   SED   |    LK  |
   USA     |    YY    |   343   |    330   |   ASD   |    HK  |
   UAE     |    XX    |   233   |    230   |   SED   |    LK  |
   IND     |    ZZ    |   123   |    230   |   SAD   |    FK  |
   IND     |    XX    |   213   |    430   |   ASD   |    KK  |
   IND     |    YY    |   433   |    870   |   GFD   |    FK  |
   USA     |    YY    |   865   |    230   |   SED   |    LK  |
   UAE     |    XX    |   976   |    430   |   SED   |    HK  |
   USA     |    ZZ    |   342   |    230   |   CCD   |    HK  |
   UAE     |    XX    |   132   |    445   |   SED   |    KK  |
   UAE     |    ZZ    |   064   |    323   |   YYD   |    LK  |
   IND     |    YY    |   452   |    130   |   ITG   |    HK  |
---------------------------------------------------------------

This is how I need to group the above table

  -------------------------------
    location |  XX  |  YY  |  ZZ  |
    -------------------------------
       UAE   |   3  |   0  |   1  |
       USA   |   1  |   2  |   1  |
       IND   |   1  |   2  |   1  |
    -------------------------------

I want to group based on location and size column, Eg: USA has 3 XX and 0 YY and 1 ZZ,

And then when i click the row i want to expand and show those 3 XX and 0 YY and 1 ZZ other four column cont_no, price, depot, cond

please someone help me or give me some suggestion or link for reference.

Thank you

Answer

Gyrocode.com picture Gyrocode.com · Jul 1, 2015

It could be done as shown in Row details example.

The trick would be to pre-process the data and perform the calculations and grouping with JavaScript before giving data to DataTables. This would depend on where your data comes from, static table or Ajax request. If you're producing the data on the server, this could be done server-side as well.

Basically the result data in JSON format could be as shown below. This will simplify working with child rows in DataTables.

[
   { 
      "location": "UAE",
      "XX": 2,
      "YY": 0,
      "ZZ": 1,
      "details": [
         ["UAE","XX","123","230","SED","LK"],
         // more records for the same location
      ]
   },
   // more locations
]