Skip to content Skip to sidebar Skip to footer

Sorting Data Attributes

I wrote a function that's supposed to sort a data-cost data attribute by price high -> low. It works fine when the data-cost all have the same amount of numbers, but if I add da

Solution 1:

You will want to use

cost: parseInt($(this).attr('data-cost'), 10)

in your object construction, so that you compare the costs as numbers not as strings.


Solution 2:

Here is a shorter way:

var sortHL = function () {
    $(".returned-list li[data-cost]").detach().sort(function(a,b){
        return Number($(a).attr('data-cost')) < Number($(b).attr('data-cost'))
    }).appendTo($(".returned-list"))
};

$('#sort').on('click', function () { 
    sortHL();
});

Solution 3:

Perform a cast:

cost: Number($(this).attr('data-cost')),

Post a Comment for "Sorting Data Attributes"