1

What am I doing wrong? It is not sorting right.

JavaScript:

function sortDescending(a, b) {
    var date1 = $(a).data('date');
    var date2 = $(b).data('date');

    return date1 > date2;
}

$('#orderaz').on('click', function () {
    $('#jo .item').sort(sortDescending).appendTo('#jo');
});

http://jsfiddle.net/agw6gvff/1/

1 Answer 1

1

A callback passed to the sort function should return a positive number if the first argument is strictly greater than the second (according to your sorting needs), a negative number if it's smaller, and 0 if they're equivalent.

You're not doing this. You're just returning whether the first argument is greater then the second. In short, you're returning a boolean, which is converted then into a number where true == 1 and false == 0.

In other words, you never return a negative value when it's needed, and this causes the issue.

Try this:

return date1 - date2;

It's a common trick for numeric sorting.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.