user3117628
user3117628

Reputation: 786

Jquery How to sort table based on calculation

var TableToSort = $("#units_table");
var ItemsWithTheData = $("#units_table .row_marker"); //Gives tbodys

var SomeCalculation = ItemsWithTheData.find("tr td:eq(0)").text() / 5;

//Sort table based on SomeCalculation result?

I simplified my calculations. You can find the real calculations in this fiddle:

http://jsfiddle.net/z6Rd8/8/

I want to sort the table based off the results of that calculation. How should I approach this problem?

Thank you.

Upvotes: 0

Views: 67

Answers (2)

juvian
juvian

Reputation: 16068

Another way of doing it(thanks joe Frambach for metric function):

var from = $("#from").val().split("|");
var metric = function (row) {
    var to = $(row).find('tr td:eq(0)').text().match(/\d+\|\d+/).toString().split("|");
    return Math.sqrt(Math.pow(parseInt(to[0]) - parseInt(from[0]), 2) + Math.pow(parseInt(to[1]) - parseInt(from[1]), 2));
};

$(".row_marker").detach().sort(function (a, b) {
    $(a).attr("data-metric", metric(a));//optional, remove if you want
    $(b).attr("data-metric", metric(b));//optional, remove if you want
    return metric(b) - metric(a);

}).appendTo('#units_table');

Upvotes: 1

000
000

Reputation: 27247

To sort elements, a good way is to detach the elements, then sort them in memory, then attach them again.

Detach: https://api.jquery.com/detach/

Append: https://api.jquery.com/append/

Here is an updated fiddle: http://jsfiddle.net/z6Rd8/9/

$("#filterdoeldorp").click(function(){

    var $table = $('#units_table');

    var from = $("#from").val().split("|");

    var rows = $table.find(".row_marker").detach();

    var metric = function(row) {
        var to = $(row).find('tr td:eq(0)').text().match(/\d+\|\d+/).toString().split("|");
        return Math.sqrt(Math.pow(parseInt(to[0])-parseInt(from[0]),2)+Math.pow(parseInt(to[1])-parseInt(from[1]),2));
    };

    rows.sort(function(a,b){
        var metric_a = metric(a);
        var metric_b = metric(b);
        return metric_a < metric_b ? -1 : metric_a > metric_b ? 1 : 0;
    });

    $.each(rows, function() {
        $table.append($(this));
    });

})

Upvotes: 1

Related Questions