I would like to know how to make a new DataTable from an existing DataTable?
Use case:
I have a proxyTable which is hidden and connected to a CategoryFilter. This is used used to construct other tables on the page which are all linked to one CategoryFilter.
Goal:
Include a Grand Total row in each new table which reflects summation of the filtered selection.
Initial solution:
I have tried extracting an array from sourceData, creating a new data table called dataResults, adding grand total row to dataResults, and drawing the final table. It works but seems like a lot of effort.
var sourceData = proxyTable.getDataTable();
var rowCount = sourceData.getNumberOfRows();
var colCount = sourceData.getNumberOfColumns();
var tempRow = [];
var tempArray = [];
var pushValue;
//push header row
for (var k = 0; k < colCount; k++) {
pushValue = sourceData.getColumnLabel(k);
tempRow.push(pushValue);
}
tempArray.push(tempRow);
tempRow = []; //reset
//push data rows
for (var i = 0; i < rowCount; i++) {
for (var j = 0; j < colCount; j++) {
pushValue = sourceData.getValue(i, j);
tempRow.push(pushValue);
}
tempArray.push(tempRow);
tempRow = []; //reset
}
//Create new Google DataTable from Array
var dataResults = new google.visualization.arrayToDataTable(tempArray);
My question:
How can I make a data table which contains all records from sourceData without going through the above steps I've tried?
You guidance is appreciated greatly!
Working Example:
UPDATE:
Added var dataResults = sourceData.clone(); per answer from #WhiteHat and I get an error sourceData.clone is not a function
Did I get the syntax wrong? Perhaps it's the ChartWrapper I'm using?
UPDATE 2:
Added var dataResults = sourceData.toDataTable().clone(); per answer #2 from #WhiteHat and it works.
google.charts.load('current', {
'packages': ['corechart', 'table', 'gauge', 'controls', 'charteditor']
});
$(document).ready(function() {
renderChart_onPageLoad();
});
function renderChart_onPageLoad() {
google.charts.setOnLoadCallback(function() {
drawDashboard();
});
}
function drawDashboard() {
var data = google.visualization.arrayToDataTable([
['Name', 'RoolNumber', 'Gender', 'Age', 'Donuts eaten'],
['Michael', 1, 'Male', 12, 5],
['Elisa', 2, 'Female', 20, 7],
['Robert', 3, 'Male', 7, 3],
['John', 4, 'Male', 54, 2],
['Jessica', 5, 'Female', 22, 6],
['Aaron', 6, 'Male', 3, 1],
['Margareth', 7, 'Female', 42, 8],
['Miranda', 8, 'Female', 33, 6]
]);
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard'));
var categoryPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'categoryPicker',
options: {
filterColumnLabel: 'Gender',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: false
}
}
});
var proxyTable = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'proxyTable',
options: {
width: '500px'
}
});
var table = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'table',
options: {
width: '500px'
}
});
dashboard.bind([categoryPicker], [proxyTable]);
dashboard.draw(data);
google.visualization.events.addListener(dashboard, 'ready', function() {
redrawChart();
});
function redrawChart() {
var sourceData = proxyTable.getDataTable();
//WhiteHat suggestion2 - WORKS
var dataResults = sourceData.toDataTable().clone();
//WhiteHat suggestion1 - Didn't work
//var dataResults = sourceData.clone();
//INITIAL SOLUTION - works
//var rowCount = sourceData.getNumberOfRows();
//var colCount = sourceData.getNumberOfColumns();
//var tempRow = [];
//var tempArray = [];
//var pushValue;
//for (var k = 0; k < colCount; k++) {
//pushValue = sourceData.getColumnLabel(k);
//tempRow.push(pushValue);
//}
//tempArray.push(tempRow);
//tempRow = []; //reset
//push data rows
//for (var i = 0; i < rowCount; i++) {
//for (var j = 0; j < colCount; j++) {
//pushValue = sourceData.getValue(i, j);
//tempRow.push(pushValue);
//}
//tempArray.push(tempRow);
//tempRow = []; //reset
//}
//var dataResults = new google.visualization.arrayToDataTable(tempArray);
var group = google.visualization.data.group(sourceData, [{
// we need a key column to group on, but since we want all rows grouped into 1,
// then it needs a constant value
column: 0,
type: 'number',
modifier: function() {
return 1;
}
}], [{
column: 1,
id: 'SumRool',
label: 'SumRool',
type: 'number',
aggregation: google.visualization.data.sum
}, {
column: 3,
id: 'SumAge',
label: 'SumAge',
type: 'number',
aggregation: google.visualization.data.sum
}, {
// get the average age
column: 4,
id: 'SumEaten',
label: 'SumEaten',
type: 'number',
aggregation: google.visualization.data.sum
}]);
dataResults.insertRows(0, [
['Grand Total', group.getValue(0, 1), null, group.getValue(0, 2), group.getValue(0, 3)],
]);
//Set dataTable
table.setDataTable(dataResults);
table.draw();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard">
<div id="categoryPicker"></div><br /> Proxy Table<br />
<div id="proxyTable"></div><br /> Table
<br />
<div id="table"></div><br /><br />
</div>
data table method --> clone()
var newDataTable = oldDataTable.clone();
from the docs...
clone() - Returns a clone of the data table. The result is a deep copy of the data table except for the cell properties, row properties, table properties and column properties, which are shallow copies; this means that non-primitive properties are copied by reference, but primitive properties are copied by value.
Related
I have following JSON data for Chart
var chartJson = [
{
header : '2016',
values : [1, 5, 9]
},
{
header : '2017',
values : [2, 4, 8]
},
{
header : '2018',
values : [3, 1, 5]
}
];
And needs to convert it into this format to feed my HTML table
var tableJson = [
{
2016 : 1,
2017 : 2,
2018 : 3
},
{
2016 : 5,
2017 : 4,
2018 : 1
},
{
2016 : 9,
2017 : 8,
2018 : 5
}
];
Any quick help will be appreciated to convert it into this format.
I tried using this code, but somehow missing on the logic.
let table = [];
for(var row of chartJson ){
for(var value of row.values)
{
table.push(
{
column : row.header,
value : value
});
}
}
var chartJson = [{
header: '2016',
values: [1, 5, 9]
},
{
header: '2017',
values: [2, 4, 8]
},
{
header: '2018',
values: [3, 1, 5]
}
];
let table = [];
chartJson.forEach((row, index) => {
row.values.forEach((val, j) => {
table[j] = { ...table[j],
[row.header]: val
}
});
});
console.log(table)
Iterate through every chartJson's element with its' values(through inner loop) till values' length and make an object from that.
Finally, push that object into the table array.
That's it.
Have a look at the snippet below:
var chartJson = [
{
header: '2016',
values: [1, 5, 9]
},
{
header: '2017',
values: [2, 4, 8]
},
{
header: '2018',
values: [3, 1, 5]
}
];
let table = [];
let len_of_chartJson = chartJson.length, len_of_values = chartJson[0].values.length;
for (var i = 0; i < len_of_chartJson; i++) {
let obj = {};
for (var j = 0; j < len_of_values; j++) {
obj[chartJson[j].header] = chartJson[j].values[i];
}
table.push(obj);
}
console.log(table);
let table = chartJson.reduce((tbl, rec) => {
rec.values.forEach((num, index) => {
if(!tbl[index]){
tbl[index] = {}
}
tbl[index][rec.header] = num
})
return tbl
}, [])
Array reduce function is used to loop through each object, than for each object it loop through each value, checking if the index exist in the table, if it does not exist, it create an empty object at current index. Finally it creates a key value in the current index object.
You read more about reduce function below
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
I want to increase the count of 4 different variables to fill in a pie chart. But i only want it to increment the variables per unique variable in the 2 columns. I want to try to make them distinct but i do not quite understand how to. In the if statement i try to compare the value with a string. This works. After the || i try to make it distinct but i have trouble with that.
Here is my code:
function createPiechartthree(){
var columns = {};
var xmlColumns = $j('head', xml);
xmlColumns.find('headColumn').each(function(){
var columnName = $j(this).find('columnValue').text();
var columnID = $j(this).attr('columnid');
columns[columnName] = (columnID);
});
var xmlData = $j('data', xml);
xmlData.find('item').each(function(){
$j(this).find('column').each(function(){
var colID = $j(this).attr("columnid");
console.log(colID);
var value = $j(this).find('displayData').text();
if(colID == columns["Risk level client"] || colID == columns["Counterparty name"] ){
if(value === "High" || value === value){
highRiskCategory++;
}
else if(value === "Medium" || value === value){
mediumRiskCategory++;
}
else if(value === "Low" || value === value){
lowRiskCategory++;
} else if(value === "" || value === value) {
unidentified++;
}
}
})
})
1) rather than incrementing the counts manually, build an array of the values found...
var riskData = [
['Starbucks', 'High'],
['Starbucks', 'High'],
['McDonalds', 'Low'],
['Dunkin', 'Medium'],
['Dunkin', 'Medium'],
['Dunkin', 'Medium'],
['Subway', 'Low'],
['Chick-fil-a', ''],
['Chick-fil-a', '']
];
2) then filter out the duplicates...
var pieData = new google.visualization.DataTable();
pieData.addColumn('string', 'Risk Level');
var counterParty = [];
riskData.forEach(function (riskLevel) {
if (counterParty.indexOf(riskLevel[0]) === -1) {
counterParty.push(riskLevel[0]);
var rowData = (riskLevel[1] === '') ? ['Unidentified'] : [riskLevel[1]];
pieData.addRow(rowData);
}
});
3) then use google's group method to aggregate the counts...
var groupPie = google.visualization.data.group(
pieData,
[0],
[{
aggregation: google.visualization.data.count,
column: 0,
label: 'Count',
type: 'number'
}]
);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['controls']
});
function drawChart() {
// create array like this
var riskData = [
['Starbucks', 'High'],
['Starbucks', 'High'],
['McDonalds', 'Low'],
['Dunkin', 'Medium'],
['Dunkin', 'Medium'],
['Dunkin', 'Medium'],
['Subway', 'Low'],
['Chick-fil-a', ''],
['Chick-fil-a', '']
];
// for example only <--
var tableRisk = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'table_risk',
dataTable: google.visualization.arrayToDataTable(riskData, true)
});
tableRisk.draw();
// -->
var pieData = new google.visualization.DataTable();
pieData.addColumn('string', 'Risk Level');
var counterParty = [];
riskData.forEach(function (riskLevel) {
if (counterParty.indexOf(riskLevel[0]) === -1) {
counterParty.push(riskLevel[0]);
var rowData = (riskLevel[1] === '') ? ['Unidentified'] : [riskLevel[1]];
pieData.addRow(rowData);
}
});
// for example only <--
var tablePie = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'table_pie',
dataTable: pieData
});
tablePie.draw();
// -->
var groupPie = google.visualization.data.group(
pieData,
[0],
[{
aggregation: google.visualization.data.count,
column: 0,
label: 'Count',
type: 'number'
}]
);
// for example only <--
var tablePie = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'table_group',
dataTable: groupPie
});
tablePie.draw();
// -->
var chartPie = new google.visualization.ChartWrapper({
chartType: 'PieChart',
containerId: 'chart_pie',
dataTable: groupPie,
options: {
colors: ['red', 'orange', 'green', 'blue']
}
});
chartPie.draw();
}
div {
display: inline-block;
margin-right: 8px;
vertical-align: top;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_risk"></div>
<div id="table_pie"></div>
<div id="table_group"></div>
<div id="chart_pie"></div>
Please refer to the following link:
http://jsfiddle.net/RjHMH/46/
I am using google visualization table, and making a tree table like above. Some column in child row, I attached html checkbox.
I question I am facing is that, if I click the checkbox, it is never checked. This is because in the table listener, every time a select event is triggered, it will redraw the table.
I look at the google visualization table API, and find this:
Note that the table chart only fires row selection events; however,
the code is generic, and can be used for row, column, and cell
selection events.
This means that if I click a column in row, I can never know which column I actually clicked? So I can not get the checkbox by id, and using javascript to make it checked? That sucks...
Indeed, getSelection() function does not preserve column once select event is triggered. But you could consider the following approach to preserve checkboxes states once the chart is redrawn.
First, we need to introduce object for storing checkboxes states:
var checkboxStates = {'cbox1' : false, 'cbox2': false};
Then we register ready event for saving/loading state once Google Chart is redrawn:
google.visualization.events.addOneTimeListener(table, 'ready', function(){
//...
});
And finally the following example demonstrates how to save/load state:
//load checkboxes state
for(var id in checkboxStates){
var checkbox = document.getElementById(id);
if(checkbox !== null) {
checkbox.checked = checkboxStates[id];
}
}
//save state
if(event.target.type == "checkbox"){
var checkbox = document.getElementById(event.target.id);
checkbox.checked = !event.target.checked;
checkboxStates[event.target.id] = checkbox.checked;
}
Note: Event.target is utilized to track checkboxes click events
Final example
Below is provided the modified example of yours with ability to preserve checkboxes state
google.load('visualization', '1', {
packages: ['table']
});
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'id');
data.addColumn('string', 'parentId');
data.addColumn('boolean', 'visible');
data.addColumn('number', 'level');
data.addColumn('string', 'Name');
data.addColumn('number', 'Value');
data.addRows([
['1', null, true, 1, 'Foo', 10],
['1.1', '1', false, 2, 'Foo 1', 2],
['1.1.1', '1.1', false, 3, 'Foo 1a', 2],
['1.1.2', '1.1', false, 3, 'Foo 1b', 2],
['1.2', '1', false, 2, 'Foo 2', 3],
['1.3', '1', false, 2, 'Foo 3', 5],
['1.3.1', '1.3', false, 3, '<input type="checkbox" id="cbox1" value="second_checkbox">', 1],
['1.3.2', '1.3', false, 3, '<input type="checkbox" id="cbox2" value="second_checkbox">', 4],
['2', null, true, 1, 'Bar', 14],
['2.1', '2', false, 2, 'Bar 1', 6],
['2.2', '2', false, 2, 'Bar 2', 7],
['2.2.1', '2.2', false, 3, 'Bar 2a', 3],
['2.2.2', '2.2', false, 3, 'Bar 2b', 2],
['2.2.3', '2.2', false, 3, 'Bar 2c', 2]
]);
// get all rows with children
// start by finding all child rows (ie, rows with parents)
var children = data.getFilteredRows([{
column: 1,
minValue: '1'
}]);
var parentsArray = [];
var parentId;
// identify the parents of all children
for (var i = 0; i < children.length; i++) {
parentId = data.getValue(children[i], 1);
if (parentsArray.indexOf(parentId) === -1) {
parentsArray.push(parentId);
}
}
//format the parent rows
var parent = data.getFilteredRows([{
column: 3,
value: 1
}]);
for (var j = 0; j < parent.length; j++) {
parentId = data.getValue(parent[j], 0);
if (parentsArray.indexOf(parentId) !== -1) {
data.setProperty(parent[j], 4, 'className', 'parentcl close');
}
else {
data.setProperty(parent[j], 4, 'className', 'parentcl');
}
};
//format the 2level rows
var leveltwo = data.getFilteredRows([{
column: 3,
value: 2
}]);
for (var j = 0; j < leveltwo.length; j++) {
parentId = data.getValue(leveltwo[j], 0);
if (parentsArray.indexOf(parentId) !== -1) {
data.setProperty(leveltwo[j], 4, 'className', 'leveltwo close');
}
else {
data.setProperty(leveltwo[j], 4, 'className', 'leveltwo');
}
};
//format the 3level rows
var levelthree = data.getFilteredRows([{
column: 3,
value: 3
}]);
for (var j = 0; j < levelthree.length; j++) {
data.setProperty(levelthree[j], 4, 'className', 'levelthree');
};
var view = new google.visualization.DataView(data);
// hide the first four columns
view.setColumns([4, 5]);
view.setRows(data.getFilteredRows([{
column: 2,
value: true
}]));
var table = new google.visualization.Table(document.getElementById('table_div'));
var cssClassNames = {
headerRow: 'gtableheader',
oddTableRow: 'rowodd',
headerCell: 'gtableheader'
};
var options = {
showRowNumber: false,
allowHtml: true,
cssClassNames: cssClassNames,
sort: 'disable'
};
var checkboxStates = {'cbox1' : false, 'cbox2': false};
google.visualization.events.addListener(table, 'select', function () {
var sel = table.getSelection();
recurseTree(view.getTableRowIndex(sel[0].row), false);
view.setRows(data.getFilteredRows([{
column: 2,
value: true
}]));
table.setSelection(null);
google.visualization.events.addOneTimeListener(table, 'ready', function(){
//load checkboxes state
for(var id in checkboxStates){
var checkbox = document.getElementById(id);
if(checkbox !== null) {
checkbox.checked = checkboxStates[id];
}
}
//update state
if(event.target.type == "checkbox"){
var checkbox = document.getElementById(event.target.id);
checkbox.checked = !event.target.checked;
checkboxStates[event.target.id] = checkbox.checked;
}
});
table.draw(view, options);
function recurseTree(row, hideOnly) {
// get the id of the row
var id = data.getValue(row, 0);
// get the parent row
var parentrow = data.getFilteredRows([{
column: 0,
value: id
}]);
var parentlevel = data.getValue(parentrow[0], 3);
// find all child rows
var rows = data.getFilteredRows([{
column: 1,
value: id
}]);
for (var i = 0; i < rows.length; i++) {
if (data.getValue(rows[i], 2)) {
// hide the row and recurse down the tree
data.setValue(rows[i], 2, false);
switch (parentlevel) {
case 1:
data.setProperty(parentrow[0], 4, 'className', 'parentcl close');
break;
case 2:
data.setProperty(parentrow[0], 4, 'className', 'leveltwo close');
break;
default:
data.setProperty(parentrow[0], 4, 'className', 'levelthree close');
}
recurseTree(rows[i], true);
}
else if (!hideOnly) {
// if the row is hidden, show it
data.setValue(rows[i], 2, true);
switch (parentlevel) {
case 1:
data.setProperty(parentrow[0], 4, 'className', 'parentcl open');
break;
case 2:
data.setProperty(parentrow[0], 4, 'className', 'leveltwo open');
break;
default:
data.setProperty(parentrow[0], 4, 'className', 'levelthree open');
}
}
}
}
});
table.draw(view, options);
}
.parentcl{
font-weight: bold !important;
}
.close:before{
content:"→ "
}
.open:before{
content:"↘ "
}
.leveltwo{
padding-left: 20px !important;
}
.levelthree{
padding-left: 45px !important;
font-style:italic;
}
.gtableheader {
font-weight: bold;
background-color: grey;
}
.rowodd {
background-color: beige;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="table_div"></div>
Here I have google visualisation datatable:
How I can add here new Row and on postion [0] to put string "Sum" in position 1 will be 10, in position [2] will be 17, as sum of columns...
I start to write code but I'n not going anywhere ...
I try:
data.addRow();
for (var x=1, maxcol=data.getNumberOfColumns(); x < maxcol; x++) {
for y=1, maxrow=data.getNumberOfRows(); y < maxrow; y++) {
//WHAT NEXT ???
Try this:
var group = google.visualization.data.group(data, [{
type: 'number',
column: 0,
modifier: function () {return 0;}
}], [{
type: 'number',
column: 1,
aggregation: google.visualization.data.sum
}, {
type: 'number',
column: 2,
aggregation: google.visualization.data.sum
}]);
data.addRow(['Sum', group.getValue(0, 1), group.getValue(0, 2)]);
[Edit - added code to handle an arbitrary number of columns]
var groupColumns = [];
for (var i = 1; i < data.getNumberOfColumns(); i++) {
groupColumns.push({
type: 'number',
column: i,
aggregation: google.visualization.data.sum
});
}
var group = google.visualization.data.group(data, [{
type: 'number',
column: 0,
modifier: function () {return 0;}
}], groupColumns);
var row = ['Sum'];
for (var i = 1; i < group.getNumberOfColumns(); i++) {
row.push(group.getValue(0, i));
}
data.addRow(row);
I'm in a MVC application, and I'm having problems to generate a chart in highchart, I have this code
foreach (var item in query)
{
object[] values = new object[3];
values[0] = i;
values[1] = Convert.ToDecimal(item.ini) ;
values[2] = Convert.ToDecimal(item.ir);
dataResult.Add(values);
}
generates the following:
passed to the json which returns me this chart
What I like is that the value of "IRI201308NF3" was the name of the series and the other two values gerarariam the correct chart.
Under the Json
$.getJSON("/GrafLev/GetDadosByGraficos", { parameter },
function (data) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
ignoreHiddenSeries: false
},
yAxis: {
title: {
text: 'Exchange rate'
},
plotLines: [{
value: limInferior,
color: 'green',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Inferior'
}
}, {
value: limSuperior,
color: 'red',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Superior'
}
}]
},
xAxis: {
},
series: [{ data: data }]
});
});
I found this example, but I can not format.
The only thing is that the graph is a line.
Reading the Highcharts api, it's series parameter is looking for an array of dictionaries with a name and data property. You are passing the data property a mixed array. Now, you could reformat the response JSON in the javascript, but I think it's cleaner to format the JSON properly in the C#:
Dictionary<string, object> dataResult = new Dictionary<string, object>();
dataResult["data"] = new List<object[]>();
dataResult["name"] = i;
foreach (var item in query)
{
object[] values = new object[2];
values[0] = Convert.ToDecimal(item.ini) ;
values[1] = Convert.ToDecimal(item.ir);
((List<object[]>)dataResult["data"]).Add(values);
}
This will result in JSON looking like this:
{"data":[[0,0],[1,10],[2,20],[3,30],[4,40],[5,50],[6,60],[7,70],[8,80],[9,90]],"name":"Hi Mom"}
Now you should be good to pass this to the series parameter as:
series: [ data ]
Note, this JSON is still returning a single series. If you need to return multiple series, just comment and I'll modify the code.
EDITS
For multiple series add an outer list containing each series Dictionary<string, object>.
Here's an example:
List<Dictionary<string, object>> dataResult = new List<Dictionary<string, object>>();
for (int i = 1; i <= 2; i++)
{
Dictionary<string, object> aSeries = new Dictionary<string, object>();
aSeries["data"] = new List<object[]>();
aSeries["name"] = "Series " + i.ToString();
for (int j = 0; j < 10; j++)
{
object[] values = new object[2];
values[0] = j;
values[1] = j * 10 * i;
((List<object[]>)aSeries["data"]).Add(values);
}
dataResult.Add(aSeries);
}
Pass to Highcharts as:
series: data