0

i have to deal with an array of object representing an unordered collection of date and time(i can't modify the structure) and sort it by the most recent date.

the structure look like this:

{
  "H": 5,
  "Date": {
    Y: 2015
    M: 3,
    D: 21
  }
}

So, like i said, i have to sort it from the most recent Date/Hour first.

Thanks in advance!

SlashJ
  • 687
  • 1
  • 11
  • 31
  • 5
    What have you tried so far? Can you provide some code showing your attempts so that we can help? – Alex McMillan May 31 '15 at 19:48
  • You can do this with [Array.sort](http://stackoverflow.com/a/5002924/184595). In the callback function, create a `Date` object for `x` and `y` – CrayonViolent May 31 '15 at 19:51
  • 1
    Where is your question? You don't really ask anything. Don't say "please write my code" because this is not a coding service site. – pid May 31 '15 at 19:51

1 Answers1

2

You could read it here on MDN

Array has a sort function :

arr.sort([compareFunction])

Assuming you 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 it with a functionj that takes 2 argument - each of them is an object to compare :

for example

If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.

So you can now create 2 dates to 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 to notice that

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

will yield a number :

86400000

while

new Date(1978,11,22)

will yield another representation

Fri Dec 22 1978 00:00:00 GMT+0200 (Jerusalem Standard Time)

(depending on local environment)

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

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • The code may work, but a block of hard-to-read code with meaningless variable names and no explanation is not a good answer. – lonesomeday May 31 '15 at 19:55