Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

javascript - Sorting by date with underscore.js or just plain JS

I have an array of objects that have a 'date' string property. ie:

[
    {
        id: 1,
        startDate: '2011-4-22'
    },
    {
        id: 2,
        startDate: '2012-3-15'
    },
    {
        id: 3,
        startDate: '2011-4-22'
    },
    {
        id: 4,
        startDate: '2012-2-10'
    }
]

I just want to convert the date strings to a date and sort them by startDate DESC. Can someone please tell me how to do this with teh underscore.js _sortBy method or even just plain javascript will do.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An Underscore solution could look like this:

a = [ /* ... */ ];

function to_date(o) {
    var parts = o.startDate.split('-');
    o.startDate = new Date(parts[0], parts[1] - 1, parts[2]);
    return o;
}
function desc_start_time(o) {
    return -o.startDate.getTime();
}
var b = _.chain(a)
         .map(to_date)
         .sortBy(desc_start_time)
         .value();

You don't have to use named functions of course but the names do make the logic a bit clearer.

Demo: http://jsfiddle.net/ambiguous/qe9sZ/

In plain JavaScript you could do it like this:

for(var i = 0, parts; i < a.length; ++i) {
    parts = a[i].startDate.split('-');
    a[i].startDate = new Date(parts[0], parts[1] - 1, parts[2]);
}
var b = a.sort(function(a, b) {
    return b.startDate - a.startDate;
});

Demo: http://jsfiddle.net/ambiguous/rPAPG/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...