Search code examples
javascriptextjsextjs4sencha-touchstore

Extjs Store all fields average


I have a store like below

Ext.define('Result', {
    extend: 'Ext.data.Model',
    fields: [
        { name: 'state', type: 'string', mapping:0 },
        { name: 'product', type: 'string', mapping:1 },
        { name: 'quantity', type: 'int', mapping:2 }
        { name: 'price', type: 'int', mapping:3 }
    ]
});
var store = Ext.create('Ext.data.ArrayStore', {
    model: 'Result',
    groupField: 'state',
    data: [
        ['MO','Product 1',50,40],
        ['MO','Product 2',75,50],
        ['MO','Product 3',25,60],
        ['MO','Product 4',125,70],
        ['CA','Product 1',50,50],
        ['CA','Product 2',100,40],
        ['WY','Product 1',250,40],
        ['WY','Product 2',25,50],
        ['WY','Product 3',125,86],
        ['WY','Product 4',175,83]
    ]
});

I want to calculate the average of quantity and price of every state group and show it into the grid . I have seen in the sencha documentation, there is a function like average(http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.Store-method-average) and I can Implement it like

store.avarage('quantity', true);

but it only gives the average of only one field .

How and I calculate the average of multiple fields depending on the group and show it in a grid.


Solution

  • this will give you a grid with average data only: http://jsfiddle.net/Jandalf/Wn4UY/4/

    var chartStore = Ext.create('Ext.data.ArrayStore', {
        fields: ['state',  'product', 'quantity', 'price'],
        groupField: 'state',
        data: [
            ['MO','Product 1',50,40],
            ['MO','Product 2',75,50],
            ['MO','Product 3',25,60],
            ['MO','Product 4',125,70],
            ['CA','Product 1',50,50],
            ['CA','Product 2',100,40],
            ['WY','Product 1',250,40],
            ['WY','Product 2',25,50],
            ['WY','Product 3',125,86],
            ['WY','Product 4',175,83]
        ]
    });
    
    var data = [];
    var quantities = chartStore.average("quantity", true);
    var prices = chartStore.average("price", true);
    Ext.each(chartStore.collect('state'), function(item){
        data.push({
            state: item,
            quantity: quantities[item],
            price: prices[item]
        });
    });
    
    var gridStore = Ext.create('Ext.data.Store', {
        fields: ['state', 'quantity', 'price'],
        groupField: 'state',
        data: data
    });
    
    Ext.create('Ext.grid.Panel', {
        renderTo: document.body,
        store: gridStore,
        columns: [
            { dataIndex: 'state', text: 'State' },
            { dataIndex: 'quantity', text: 'Quantity' },
            { dataIndex: 'price', text: 'Price' }
        ]
    });
    

    if you want a chart with a different grouping you need a extra store, you can't define 2 'views' for a store.