javascript 使用 underscore.js 或纯 JS 按日期排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10238127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:09:42  来源:igfitidea点击:

Sorting by date with underscore.js or just plain JS

javascriptunderscore.js

提问by 29er

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

我有一组具有“日期”字符串属性的对象。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.

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

Thanks!

谢谢!

回答by mu is too short

An Underscore solution could look like this:

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

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/

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

In plain JavaScript you could do it like this:

在纯 JavaScript 中,您可以这样做:

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/

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

回答by Ry-

forEachand sortshould handle that for you:

forEach并且sort应该为您处理:

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

var i, c;

for(i = 0; c = data[i]; i++) {
    var parts = c.startDate.split('-');

    c.startDate = new Date(+parts[0], +parts[1] - 1, +parts[2]);
}

data.sort(function(a, b) {
    return b.startDate - a.startDate;
});

Here's a demo; check your console.

这是一个演示;检查您的控制台。

回答by Sanchitos

I did it this way:

我是这样做的:

 var sorted = _(list).sortBy(
                    function (item) {                        
                        return [new Date(item.effectiveDate).getTime(), item.batchId];
                    }), "batchId");

If you want it descending then it's the same thing but *-1

如果你想让它下降,那么它是一样的,但 *-1

 var sorted = _(list).sortBy(
                    function (item) {                        
                        return [new Date(item.effectiveDate).getTime()*-1, item.batchId];
                    }), "batchId");

In this example I am ordering by two fields, you can forget about the item.batchId.

在此示例中,我按两个字段排序,您可以忘记 item.batchId。

Hope this helps someone.

希望这可以帮助某人。

回答by Prajyot Khandeparkar

If you are fetching datetime field from database then you can convert the datetime to timestamp and then sort. And then reverse the array.

如果您从数据库中获取日期时间字段,那么您可以将日期时间转换为时间戳,然后进行排序。然后反转数组。

const _ = require('underscore');

var object = [{title:"a", date:"2018-03-22T09:10:21.000Z"}, {title:"b", date:"2018-08-22T09:10:21.000Z"}, {title:"c", date:"2018-04-22T09:10:21.000Z"}];

withTimeStamp = _.map(object, function(val, key){ 
  val.timestamp = new Date(val.date).getTime();
  return val; 
 });

object = _.sortBy(object, 'timestamp');
object.reverse();

console.log(object);