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!

3
  • 5
    What have you tried so far? Can you provide some code showing your attempts so that we can help? Commented May 31, 2015 at 19:48
  • You can do this with Array.sort. In the callback function, create a Date object for x and y Commented May 31, 2015 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. Commented May 31, 2015 at 19:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

The code may work, but a block of hard-to-read code with meaningless variable names and no explanation is not a good answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.