Search code examples
javascriptarrayshandlebars.jshelper

Group of category using handlebar helper and javascript


I use handlebar templates for nodejs application and need to group the result value by category. FOllowing is my data after render. The group should be of two levels

  { "manu":"Maruti","Fuel":"petrol","name":"X1","price":"rupees","seats":"6"},
  { "manu":"Maruti","Fuel":"petrol","name":"F1","price":"rupees","seats":"7"},
  { "manu":"Maruti","Fuel":"Disel","name":"E1","price":"rupees","seats":"5"},
  { "manu":"Toyato","Fuel":"Disel","name":"R3","price":"rupees","seats":"6"},
  { "manu":"Toyato","Fuel":"Disel","name":"G4","price":"rupees","seats":"4"},
  { "manu":"Kia","Fuel":"petrol","name":"W5","price":"rupees","seats":"6"}

i am able to achieve first level of grouping and struggling for the 2nd level. The expected result

-Manu
   -Fuel
      -Name, Price, Seats

result = v1.reduce(function (r, a) {
            r[a.c_group] = r[a.c_group] || [];
            r[a.c_group].push(a);
            return r;
        }, Object.create(null));

    console.log(result);

Solution

  • Let me know if this is what you want:

    var data=[{ "manu":"Maruti","Fuel":"petrol","name":"X1","price":"rupees","seats":"6"}, { "manu":"Maruti","Fuel":"petrol","name":"F1","price":"rupees","seats":"7"}, { "manu":"Maruti","Fuel":"Disel","name":"E1","price":"rupees","seats":"5"}, { "manu":"Toyato","Fuel":"Disel","name":"R3","price":"rupees","seats":"6"}, { "manu":"Toyato","Fuel":"Disel","name":"G4","price":"rupees","seats":"4"}, { "manu":"Kia","Fuel":"petrol","name":"W5","price":"rupees","seats":"6"}];
    
    var result = data.reduce((acc, {manu, Fuel, ...rest})=>{
        acc[manu] = acc[manu] || {};
        acc[manu][Fuel] = acc[manu][Fuel] || [];
        acc[manu][Fuel].push(rest);
        return acc;
    },{});
    console.log(result);