views:

102

answers:

2

I am trying to create a table, with some grouping headers. All is well when i have 1 group, but how do i create dynamic groups?

This is what i have so far (for 1 group):

var groupby = '';
arrdata.each(function(element){
    if (groupby != element.groupby) {
     groupby = element.groupby;
     tbody.push(groupby)
    }
    tbody.push(element)
})

How do i make it create dynamic groups?

A: 

try with this structure:

arrdata = [
    {
       "groupby": {fields},
       "data":[{fields},{fields},{fields}]
    },
    {
       "groupby": {fields},
       "data":[{fields},{fields},{fields}]
    },
    {
       "groupby": {fields},
       "data":[{fields},{fields},{fields}]
    },
]

jQuery.each(arrdata, function(element){
   tbody.push(element.groupby)
   jQuery.each(element.data , function(elementData){
        tbody.push(elementData);
   }) 
})
andres descalzo
Right, but that is considering that i have the data grouped in such a manner, but what if i just have the data in a bunch, and the groupby's in another bunch?
You then will have to pass an example, so it would be easier to give a solution
andres descalzo
A: 

You could group them into an Object first:

Array.prototype.groupBy = function(keyName) {
  var res = {};
  this.forEach(function(x) {
    var k = x[keyName];
    var v = res[k];
    if (!v) v = res[k] = [];
    v.push(x);
  });
  return res;
};

Then for .. in through the object:

var employees = [{first: ..., last: ..., job: ...}, ...];
var byJob = employees.groupBy('job');
for (var job in byJob) {
  document.write('<h3>Job: '+job+'</h3>');
  byJob[job].forEach(function(e) {
    document.write('<p>'+e.last+', '+e.first+'</p>');
  });
}
Simon Buchan