user1477388
user1477388

Reputation: 21420

Grouping and Counting Occurrences in Kendo UI Chart

I have a datasource with which I would like to group by item and count the occurrences in the chart.

For example, "Item 1" would have a count of 2, "Item 2" would have a count of 3, and "Item 3" would have a count of 1.

http://jsfiddle.net/mga6f/506/

I have tried adding group but it still won't work:

group: [{
    field: "item"
}],

Does anyone know how I can modify the following code to perform the functionality described above?

var dataSource = new kendo.data.DataSource({
    data: [
        { id: 1, item: "Item 1" },
        { id: 2, item: "Item 1" },
        { id: 3, item: "Item 2" },
        { id: 4, item: "Item 2" },
        { id: 5, item: "Item 2" },
        { id: 6, item: "Item 3" }       
    ],
    group: [{
        field: "item"
    }],
    schema: {
        model: {
            id: "id",
            fields: {
                id: { type: "number", editable: false },
                value: { type: "number" },
                item: { type: "string" }                
            }
        }            
    }
});

$("#chart").kendoChart({
    dataSource: dataSource,
    autoBind: false,
    categoryAxis: {
        field: "item"   
    },
    series: [
        { field: "value", name: "Value" }
    ]        
});

dataSource.read();

Upvotes: 1

Views: 760

Answers (1)

ezanker
ezanker

Reputation: 24738

You could use the fetch method on the grouped data source to read the data and then create a new array of items and their counts:

var transformedData = [];
dataSource.fetch(function () {
  var v = this.view();
  for (var i = 0; i < v.length; i++) {
    var item = v[i].value;
    var val = v[i].items.length;
    transformedData.push({item: item, value: val});
  }
});


$("#chart").kendoChart({
    dataSource: transformedData,
    categoryAxis: {
        field: "item"   
    },
    series: [
        { field: "value", name: "Value" }
    ]        
});

Updated FIDDLE

Upvotes: 3

Related Questions