Johnleo Johnleo - 7 months ago 21
Javascript Question

sort array by time format

<script type="text/javascript">
$.each(newPages, function(key, val){
val.sort(function(a,b){
if(a.estimatedTime > a.scheduledTime && b.estimatedTime > b.scheduledTime){
return 0;
}else if(a.estimatedTime > a.scheduledTime){
return -1;
}else if(b.estimatedTime > b.scheduledTime){
return 1;
}else{
if(a.scheduledTime > b.scheduledTime){
return 1;
}else{
return -1;
}
}
});
});
</script>


The above code i want to display according to time(sort time in ascending)
Please help me.Thanks.

Answer

If the time is a string, just sort it alphabetically.

var newPages = [{time:"18:30",msg:"I'm fine"},{time:"09:13",msg:"How are you?"},{time:"10:30",msg:"Hi"}];

var s="";

newPages.sort(function(a,b){return a.time.localeCompare(b.time);});

for(var i=0;i<newPages.length;i++){
  s+=newPages[i].time+" - "+newPages[i].msg+"\n";
}
document.getElementById("out").textContent=s;
<pre id="out"></pre>

Comments