Dann
Dann

Reputation: 117

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 data-costs that have different amounts of numbers, the function no longer works. I'd like to keep the same structure that I have now, but as I'm still relatively new to JS, I'm open to more reusable solutions. Thanks in advance for any help.

Fiddle:

http://jsfiddle.net/dn6mja0t/

HTML:

<a id="sort" href="#">Price High to Low</a>

<ul class="returned-list">
    <li data-cost="101">101</li>
    <li data-cost="103">103</li>
    <li data-cost="106">106</li>
    <li data-cost="42">42</li>
</ul>

JS:

var sortHL = function () {
    function compare(a,b) {
        if (a.cost > b.cost)
            return -1;
        if (a.cost < b.cost)
            return 1;
        return 0;
    }

    var items = [];
    $('.returned-list li').each(function() {
        var item = {
            cost: $(this).attr('data-cost'),
            contents: $(this)[0].outerHTML
        };
        items.push(item);
    });

    items.sort(compare);
    $('.returned-list').html('');
    for(var i=0;i<items.length;i++) {
        $('.returned-list').append(items[i].contents);
    }
};

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

Upvotes: 0

Views: 111

Answers (3)

juvian
juvian

Reputation: 16068

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();
});

Upvotes: 2

Verhaeren
Verhaeren

Reputation: 1661

Perform a cast:

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

Upvotes: 1

Bergi
Bergi

Reputation: 664579

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.

Upvotes: 3

Related Questions