11

If i have this markup:

<p data-date="Fri, 26 Aug 2011 20:58:39 GMT">item 1</p>
<p data-date="Fri, 24 Aug 2011 20:58:39 GMT">item 1</p>
<p data-date="Fri, 25 Aug 2011 20:58:39 GMT">item 1</p>

How could i use jQuery to order these P's by their data-date attribute?

Thanks

1
  • ascending or descending? Commented Aug 27, 2011 at 0:29

3 Answers 3

27

Demo

Super simple with an array sort:

$("p").sort(function(a,b){
    return new Date($(a).attr("data-date")) > new Date($(b).attr("data-date"));
}).each(function(){
    $("body").prepend(this);
})

Reverse order (in case I misunderstood you) is as easy as flipping the greater than symbol

$("p").sort(function(a,b){
    return new Date($(a).attr("data-date")) < new Date($(b).attr("data-date"));
}).each(function(){
    $("body").prepend(this);
})
Sign up to request clarification or add additional context in comments.

3 Comments

lol thanks, @AlienWebguy :) but whatever works works and you had your solution faster anyhow :P
This method does not appear to work in IE9. Not sure if its .sort in general but the list just reverses in IE9.
@trobbins26 I don't have IE in front of me right now. Could you try this updated version? jsfiddle.net/CQ3gg/440
3
function sortDates(a, b)
{
    return new Date(b).getTime() - new Date(a).getTime();
}

var dates = [];
var _old;

$('p').each(function(){
    _old = $(this).parent();
    dates.push($(this).data('date'));
});

var sorted = dates.sort(sortDates);
var _new = $('<div/>').insertBefore(_old);

$.each(sorted,function(i,val){
    $('p[data-date="' + val + '"]').appendTo(_new);
});

_old.remove();

Working demo: http://jsfiddle.net/AlienWebguy/JhgSw/

Comments

3

The custom function suggested in Joseph's answer (the currently accepted solution) should return a numeric value, not a boolean. See This other question where this issue has already been raised showing that this function will not work in IE.

The "dates.compare(a,b)" function defined here looks like a better fit for use in jQuery's sort method.

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.