我有一系列的物品,如下所示:
myarray = [
{
somedate: "2018-01-11T00:00:00",
name: "John Doe",
level: 6000
},
{
somedate: "2017-12-18T00:00:00",
name: "Don Jhoe",
level: 53
},
{
somedate: "2016-12-18T00:00:00",
name: "Jane Doe",
level: 100
},
{
somedate: "2018-10-18T00:00:00",
name: "Dane Joe",
level: 1
}
]
我试图弄清楚如何对该数组进行排序,以便按日期对它进行排序。我知道如何对简单属性数组进行排序:
Sort Javascript Object Array By Date
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
但是如何最好地通过其项属性对数组进行排序呢?
编辑:是的,这些确实是由不处理时间的奇怪Web服务提供的不正确的日期字符串。
答案 0 :(得分:4)
您发布的代码实际上可以正常工作。
您所需要做的就是比较somedate
而不是date
,然后将最终的排序结果分配给原始排序结果(如果需要的话)。
myarray = myarray.sort(function(a,b){
return new Date(b.somedate) - new Date(a.somedate);
});
答案 1 :(得分:0)
通过具有ISO 8601兼容日期,您可以使用字符串比较器,因为值的组织(年,月,日,小时等)是递减的,并且每个单位的长度相同。 / p>
var array = [{ somedate: "2018-01-11T00:00:00", name: "John Doe", level: 6000 }, { somedate: "2017-12-18T00:00:00", name: "Don Jhoe", level: 53 }, { somedate: "2016-12-18T00:00:00", name: "Jane Doe", level: 100 }, { somedate: "2018-10-18T00:00:00", name: "Dane Joe", level: 1 }];
array.sort(({ somedate: a }, { somedate: b }) => b.localeCompare(a)); // desc
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }