how to sort array of object from most recent date in javascript -


i have deal array of object representing unordered collection of date , time(i can't modify structure) , sort recent date.

the structure this:

{   "h": 5,   "date": {     y: 2015     m: 3,     d: 21   } } 

so, said, have sort recent date/hour first.

thanks in advance!

you read here on mdn

array has sort function :

arr.sort([comparefunction]) 

assuming have :

var myarr=[{   "h": 5,   "date": {     y: 2015,     m: 3,     d: 01   } },{   "h": 5,   "date": {     y: 2015,     m: 3,     d: 21   } },{   "h": 5,   "date": {     y: 2015,     m: 3,     d: 11   } }]; 

you can sort functionj takes 2 argument - each of them object compare :

for example

if comparefunction(a, b) less 0, sort a lower index b, i.e. comes first.

so can create 2 dates compare

myarr.sort(function (a,b){ return new date(a.date.y,a.date.m,a.date.d,a.h,0,0) - new date(b.date.y,b.date.m,b.date.d,b.h,0,0)}) 

you might want notice

new date(1978,11,22) - new date(1978,11,21)  

will yield number :

86400000

while

new date(1978,11,22) 

will yield representation

fri dec 22 1978 00:00:00 gmt+0200 (jerusalem standard time) 

(depending on local environment)

http://jsbin.com/gusokamoye/3/edit


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -