Question

So this one has me stumped. I need to take a HTML table and generate a line graph that represents the number of entries per month. I currently have DataTables creating the table for me and the source data can not be modified. I will be using Flot to generate the line graph for me. The Flot function requires a dataset as shown below.

Expected Dataset:

[ [1, 3], [2, 14], [3, 3] ]

During the DataTables function fnInitComplete I will need to generate the above dataset from the table data and pass it to the Flot function. This insures the graphs are as dynamic as the table which is a requirement.

Here is what I have so far: (incomplete DataTables function, but the rest is not needed for this question)

$(document).ready(function() {
    // The unimportant DT part
    var sTable = $('#sTable').dataTable({ ... });

    // What I currently have
    var items=[]; // The wrapper for my dataset (array)

    //Iterate all td's in eighth column
    $('#sTable tbody tr td:nth-child(8)').each( function(){

        //convert to jsDate from MySQL timestamp
        var dateParts = $(this).text().split("-");
        var jsDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2].substr(0,2));
        var n = jsDate.getMonth();
        //In my table I have March (represented as 2) five times so 
        //console.log(n); will print 2 five times.
    });
});

And this is as far as I have gotten unfortunately. I think the best approach is to take the n value and make it a variable's name so I would have a variable defined as 2 and then I could just do something like 2++. This way for each month returned as a number I will have a variable that is named after that number and it would contain the number of times it was present in the .each function. This would also limit the variables to only months that where present and will allow me to simply create the dataset I need to pass.

I don't have much experience with working with JavaScript in the manner so any help is greatly appreciated.

Was it helpful?

Solution

Create an array whichs contains each month and the count for the month starting with zero like this:

[ [1, 0], [2, 0], ..., [12, 0] ]

with this code:

var items = [];
for (var i = 1; i <= 12; i++)
    items.push([i, 0]);

And then in your each function use

items[n][1]++;

to increase the count for each occurence of the month n in your table.

After that you can use your items array to create a flot chart.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top