node.js 使用下划线 sortBy 进行对象排序的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19090626/
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
Array with object sorting with Underscore sortBy
提问by Hyman Dre
I have this array. How do I use underscore '_.sortBy' to sort it according to start date?
我有这个数组。如何使用下划线“_.sortBy”根据开始日期对其进行排序?
[
{
id: 'oljw832021kjnb389xzll323jk',
start: { dateTime: '2013-09-26T13:30:00-07:00' },
end: { dateTime: '2013-09-26T14:30:00-07:00' },
},
{
id: 'ed7l5tmckdp0lm90nvr4is3d4c',
start: { dateTime: '2013-09-26T15:30:00-07:00' },
end: { dateTime: '2013-09-26T16:30:00-07:00' },
},
{
id: 'etmasdsackdp0kjl0nvrkopioqw',
start: { dateTime: '2013-09-26T18:00:00-07:00' },
end: { dateTime: '2013-09-26T19:00:00-07:00' },
}
]
回答by Bergi
Use an iterator function, not a single string for a property:
使用迭代器函数,而不是属性的单个字符串:
_.sortBy(arr, function(o) { return o.start.dateTime; })
回答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 inshu choudhary
var sortedItem = _.sortBy(yourArrayName, ["start"])
var sortedItem = _.sortBy(yourArrayName, ["start"])

