使用underscore.js按日期排序或仅使用普通JS [英] Sorting by date with underscore.js or just plain JS

查看:283
本文介绍了使用underscore.js按日期排序或仅使用普通JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有'date'字符串属性的对象数组。
ie:

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'
    }
]

我只想转换日期字符串到日期并通过startDate DESC对它们进行排序。有人可以用teh underscore.js _sortBy方法告诉我如何做到这一点,甚至只是简单的javascript即可。

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.

谢谢!

推荐答案

Underscore解决方案可能如下所示:

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.

演示: http://jsfiddle.net/ambiguous/qe9sZ/

在纯JavaScript中你可以这样做:

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

演示: http://jsfiddle.net/ambiguous/rPAPG/

这篇关于使用underscore.js按日期排序或仅使用普通JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆