Javascript 如何按日期升序对对象进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7513040/
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
How to sort objects by date ascending order?
提问by Leem
if I have a list of object:
如果我有一个对象列表:
var objectList= LIST_OF_OBJECT;
each objectin the list contains three attributes: "name", "date","gender"
列表中的每个对象都包含三个属性:“名称”、“日期”、“性别”
How to sort the objects in the list by "date" attribute ascending order?
如何按“日期”属性升序对列表中的对象进行排序?
(the "date" attribute contain string value like "2002-08-29 21:15:31+0500")
(“日期”属性包含字符串值,如“2002-08-29 21:15:31+0500”)
回答by turdus-merula
If your objects have the dateinformation within a Stringfield:
如果您的对象在字符串字段中具有日期信息:
yourArray.sort(function(a, b) { return new Date(a.date) - new Date(b.date) })
or, if they have it within a Datefield:
或者,如果他们在日期字段中有它:
yourArray.sort(function(a, b) { return a.date - b.date })
回答by Matt
The Array.sort
method accepts a sort function, which accepts two elements as arguments, and should return:
该Array.sort
方法接受一个排序函数,它接受两个元素作为参数,并且应该返回:
- < 0 if the first is less than the second
- 0 if the first is equal to the second
- > 0 if the first is greater than the second.
- < 0 如果第一个小于第二个
- 0 如果第一个等于第二个
- > 0 如果第一个大于第二个。
.
.
objectList.sort(function (a, b) {
var key1 = a.date;
var key2 = b.date;
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
});
You're lucky that, in the date format you've provided, a date that is before another date is also <
than the date when using string comparisons. If this wasn't the case, you'd have to convert the string to a date first:
你很幸运,在你提供的日期格式中,在另一个日期之前的日期也<
比使用字符串比较时的日期。如果不是这种情况,您必须先将字符串转换为日期:
objectList.sort(function (a, b) {
var key1 = new Date(a.date);
var key2 = new Date(b.date);
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
});
回答by sd.n
yourArray.sort(function(a, b) {
a = new Date(a.date);
b = new Date(b.date);
return a >b ? -1 : a < b ? 1 : 0;
})
回答by as sdfas
You can try:
你可以试试:
<script src="https://cyberknight.000webhostapp.com/arrange.js">
var a =[-1,0,5,4,3,2,6,1,1];
var b = totzarrange(a)
console.log(b);
</script>