Javascript Dynamic Grouping

2019-04-15 01:43发布

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?

3条回答
男人必须洒脱
2楼-- · 2019-04-15 02:21

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>');
  });
}
查看更多
在下西门庆
3楼-- · 2019-04-15 02:24

More generic solution. You can use it directly. Deep copy of objects used. Please note that this solution is of polynomial time

Array.prototype.groupBy=function(property){
"use strict";function deepCopy(p) {
var c = {};
for (var i in p) {
      if (typeof p[i] === 'object') {
        c[i] = (p[i].constructor === Array)?[]:{};
        deepCopy(p[i],c[i]);
      } 
else {
        c[i] = p[i];
      }
}
return c;
}
var retarr=[];
var len=this.length;
for(var i=0;i<len;i++){
    var groupedlen=retarr.length,found=false;
    for(var j=0;j<groupedlen;j++){
        if(this[i][property]===retarr[j].key){
            retarr[j].values.push(deepCopy(this[i]));
            found=true;
            break;
        }
    }
    if (found === false) {
        retarr.push({
            key: this[i][property],
            values: []
        });
        retarr[retarr.length-1].values.push(deepCopy(this[i]));
    }
}
return retarr;    
};

test case:

var arr=[{num: 1,key:911},{num: 2,key:22},{num: 3,key:23},{num: 4,key:222},{num: 4,key:2222},{num: 2,key:2},{num: 1,key:29},{num: 3,key:26},{num: 4,key:24}];

var grouped=arr.groupBy('num');

console.log(grouped);
查看更多
不美不萌又怎样
4楼-- · 2019-04-15 02:26

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);
   }) 
})
查看更多
登录 后发表回答