DHTMLX Docs & Samples Explorer

Grouping

Sometimes incoming data are not what we want to display and need being processed before representing in a chart. For example, we've got the data with sales in different years in several companies, and we want to show total sales per companies in a chart. So, we need to get objects with the same companies and sum up their sales. Grouping helps to resolve this problem.

It allows to gather objects with the same value of defined property and to create one object with new properties.

To group the data objects you need to define the “group” property in a chart constructor or to call group() method with object as a parameter. Group object has two properties:

  • by – defines the property that need being used to group data objects,
  • map – an object that defines the properties of the grouped objects.

Here is the code for the example described above:

var chart =  new dhtmlXChart({
     view:"bar",
     container:"chart_container",
     value:"#sales#",
     label:"#id#"
});
chart.parse(data,"json");
chart.group({
      by:"#company#",
      map:{
	sales:["#sales#","sum"]
      }
});

or

var chart =  new dhtmlXChart({
     view:"bar",
     container:"chart_container",
     value:"#sales#",
     label:"#id#",
     group:{
	by:"#company#",
	map:{
	   sales:["#sales#","sum"]				
	}
     }
})
chart.parse(data,"json");

where incoming data object contains sales per year of different companies:

var data = [
	{ sales:"8.0", year:"2007", company: "company 1"},
	{ sales:"7.3", year:"2008", company: "company 1" },
	{ sales:"4.8", year:"2009", company: "company 1"},
	...
	{ sales:"5.3", year:"2009", company: "company 4"}
];

Here data are grouped by “company” property. In the result we've got new objects. The number of objects is equal to the number of companies. Each new data object has two propeties: id (company) and sales (the total sales of a certain company):

Properties of grouped objects are set by the “map” and defined by an array. The first element of this array is a template with a property from original data, the second one – the functor which needs being applied to all values of this property in a group. Grouping provides following functors:

  • “sum” – all values are summed up,
  • “max” – the maximum value in a group,
  • “min” - the minimum value in a group.

It’s possible to define custom functor.