How do I reorder many tables according to their caption?

67 Views Asked by At

I would like to reorder many tables in alphabetical sort according to their respective caption.

Example :

Currently, I have:

  1. table with caption "PHP"

  2. table with caption "Javascript"

  3. table with caption "Android"

I would like to see:

  1. table with caption "Android"

  2. table with caption "Javascript"

  3. table with caption "PHP"

I don't know how to do this.

This is my code:

$('table').each(function() {
    $caption = $(this).find('>caption');
    $table = $(this);
    $table.sort(function (a, b) {
        var $a = $(a),
        $b = $(b),
        aVal = $a.find(">caption").text().toLowerCase(),
        bVal = $a.find(">caption").text().toLowerCase();
        if (aVal < bVal) return -1;
        else if (aVal > bVal) return 1;
        else return 0;
    });
    $('#results').append($table);
});
1

There are 1 best solutions below

0
On BEST ANSWER

You cannot sort the tables while you're iterating through them.

First you can get the caption for each table, then group it with its corresponding table and push it into an array. Now sort the array and display the contents.

var tables = [];
$('table').each(function() {
    var caption = $(this).find('caption')[0];
    tables.push({
       'table' : $(this),
       'caption': $(caption).text().toLowerCase()
    });
});
tables.sort(function (tableA, tableB){
    if (tableA.caption < tableB.caption){
        return -1;
    }
    if (tableA.caption > tableB.caption){
        return 1;
    }
    return 0;
});

$.each( tables, function( index, tableObject){
    $('#results').append(tableObject.table);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <caption>Zhp</caption> </table>
<table> <caption>php</caption> </table> 
<table> <caption>Javascript</caption> </table>



<div id="results"></div>