<html>
<head>
<script src="https://unpkg.com/ag-grid-enterprise@13.3.1/dist/ag-grid-enterprise.js"></script>
</head>
<body>
<div id="myGrid" style="height: 100%;" class="ag-fresh"></div>
<script src="main.js"></script>
</body>
</html>
/**
* This is the final solution for the weighted average calculation. This example
* includes grouping of by two columns (country and type) and then calculating
* the weighted average for interest.
*
* @author Ben Northrop
*/
var columnDefs = [{
field: "all",
rowGroup: true,
hide: true
}, {
headerName: "Country",
field: "country",
rowGroup: true,
hide: true
}, {
headerName: "Type",
field: "type",
rowGroup: true,
hide: true
}, {
headerName: "Book Value",
field: "bookValue"
}, {
headerName: "Interest",
field: "interest"
}];
var gridOptions = {
columnDefs: columnDefs,
animateRows: true,
enableRangeSelection: true,
rowData: createRowData(),
enableSorting: true,
enableFilter: true,
suppressAggFuncInHeader: true,
groupUseEntireRow: false, // need this?
groupRowAggNodes: groupRowAggNodes,
groupDefaultExpanded: 2
};
/**
* Built-in callback function that's executed on each group roll-up. We use this to calculate the
* weighted average for interest which equals SUM(bookValue * interest)/ SUM(bookValue).
*
* @see https://www.ag-grid.com/javascript-grid-aggregation/#gsc.tab=0
* @see https://plnkr.co/edit/?p=preview
*/
function groupRowAggNodes(nodes) {
let result = {
bookValue: 0,
interest: 0
};
let sumBookValue = 0;
let sumProductInterest = 0;
nodes.forEach(node => {
var data = node.group ? node.aggData : node.data;
sumBookValue += data.bookValue;
sumProductInterest += (data.bookValue * data.interest);
});
result.bookValue = sumBookValue;
result.interest = sumProductInterest / sumBookValue;
return result;
}
function createRowData() {
var rowData = [{
all: 'All',
country: 'US',
type: 'Bond',
bookValue: 24,
interest: 2.4
}, {
all: 'All',
country: 'US',
type: 'Bond',
bookValue: 35,
interest: 3.1
}, {
all: 'All',
country: 'US',
type: 'Loan',
bookValue: 65,
interest: 2.5
}, {
all: 'All',
country: 'US',
type: 'Loan',
bookValue: 72,
interest: 1.8
}, {
all: 'All',
country: 'UK',
type: 'Bond',
bookValue: 68,
interest: 3.6
}, {
all: 'All',
country: 'UK',
type: 'Bond',
bookValue: 79,
interest: 4.2
}, {
all: 'All',
country: 'UK',
type: 'Loan',
bookValue: 124,
interest: 2.8
}, {
all: 'All',
country: 'UK',
type: 'Loan',
bookValue: 98,
interest: 2.6
}];
return rowData;
}
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
});