我有一个对象数组,它们具有日期和时间的属性,我试图按desc或asc排序,但它不起作用,它会混淆数组。
我的代码:
var myDateTime = [
{date: "2016-06-08 18:10:00"},
{date: "2016-04-26 20:01:00"},
{date: "2017-02-06 14:38:00"},
{date: "2017-01-18 17:30:21"},
{date: "2017-01-18 17:24:00"}
];
var sortIt = myDateTime.sort(function(a, b) {
return new Date( a.date ) < new Date( b.date );
});
答案 0 :(得分:0)
排序需要值0,1或-1。
adate = new Date(a.date)
bdate = new Date(b.date)
return adate > bdate ? -1 : adate < bdate ? 1 : 0
甚至更简单,
array.sort(function(a,b){
return new Date(b.date) - new Date(a.date);
});
答案 1 :(得分:0)
这应该可以解决问题:
library(ggplot2)
require(gridExtra)
library(gtable)
#test value
x=0:1:15
y=0:1:15
z=15:1:0
#join values
ma<-data.frame(x,y)
ma1<-data.frame(z,y)
#define graph
a<-ggplot(data=ma)+geom_line(color="red",mapping=aes(x,y))+ geom_hline(yintercept = 10,lty=3)
b<-ggplot(data=ma1)+geom_line(mapping=aes(z,y))+ geom_hline(yintercept = 10)
#Convert to gtable
a1<-ggplotGrob(a)
b1<-ggplotGrob(b)
#Work in lines, save line and remove line in before plots
line<-a1$grobs[[6]]$children[[4]]
a1$grobs[[6]]$children[[4]]<-NULL
b1$grobs[[6]]$children[[4]]<-NULL
# Merge gtables
c1<-cbind(a1,b1)
c1<-gtable_add_grob(c1,line,l=4,t=7,r=11,b=1,z=Inf)
#Print plot
grid.newpage()
grid.draw(c1)
答案 2 :(得分:0)
使用ISO 8601日期,您只能使用String#localeCompare
。
var myDateTime = [{ date: "2016-06-08 18:10:00" }, { date: "2016-04-26 20:01:00" }, { date: "2017-02-06 14:38:00" }, { date: "2017-01-18 17:30:21" }, { date: "2017-01-18 17:24:00" }];
myDateTime.sort(function (a, b) {
return a.date.localeCompare(b.date);
});
console.log(myDateTime);
.as-console-wrapper { max-height: 100% !important; top: 0; }