rolindroy rolindroy - 8 months ago 36
jQuery Question

How to read HTML <table> and sort the table content?

I have a html table with three columns [Title, Category, Sub-Category] and multiple rows . And I want to read the entire table content and make it categorized as below output.


table content is like this.

Title Category Sub
T1 C1 S1
T2 C2 S2
T3 C2 S3
T3 C1 S1
T2 C1 S3
T1 C2 S3

Here is the output format what I really need. I just want to print the above html table content in the below out put format.

T1 :
C1 : S1
C2 : S3
T2 :
C2 : S2
C1 : S3
T3 :
C2 : S3
C1 : S3

[Category] :[Sub-Category]

Please help me.


Try using associative arrays in javascript/jQuery: DEMO

var tableRowArray = $('table tr');
var titleArray = [];
var mainArray = {};
// build an associative array of the values int he table
    if($(this).children('th').length == 0) {
        var tempTitle = $(this).children('td').eq(0).text();
            mainArray[tempTitle][$(this).children('td').eq(1).text()] = $(this).children('td').eq(2).text();
        else {
            mainArray[tempTitle] = {};
            mainArray[tempTitle][$(this).children('td').eq(1).text()] = $(this).children('td').eq(2).text();
// print the formatted associative array to the page
var formattedString = "";
$.each(titleArray, function(index, value){
    formattedString += "<b>" + value + " : </b><br/>";
    for(var key in mainArray[value]) {
        formattedString += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + key + " : " + mainArray[value][key] + "<br/>";

Basically, we create an associative array from your table and then the next piece iterates through the array to print it in the format you specified (you may need to edit the set up of the array if you table structure varies from what I used the in JSfiddle).