3

I have a json array and I am trying to sort it by date before I append it.

The array looks as such:

result = [];
result.push(
  {id: 'ID', result: {url: 'test', date: '15 May 2013, 6:40 pm'}},
  {id: 'ID', result: {url: 'test', date: '20 Dec 2012, 8:00 am'}},
  {id: 'ID', result: {url: 'test', date: '29 Jun 2012, 5:47 pm'}}
);

Currently, I have managed to sort an array of dates as such:

var datearray = [
    '2011-05-26 12:00:00',
    '2016-01-26 12:00:00',
    '2011-01-26 12:00:00',
    '2012-12-08 07:00:00',
    '2011-01-26 12:00:00',
    '1995-01-05 06:00:00'
];

datearray.sort();

which gives me:

1995-01-05 06:00:00
2011-01-26 12:00:00
2011-01-26 12:00:00
2011-05-26 12:00:00
2012-12-08 07:00:00
2016-01-26 12:00:00

but Im not sure how to do the same for a complex array which contains more keys than one. I know that I should firstly format the date to YYYY-MM-DD but after im kinda messed up.

A good start would be from what I currently came up with found on jsbin: http://jsbin.com/ipatok/8/edit

6
  • 1
    On second thought the linked duplicate question goes into greater detail (no sense in repeating good information) Commented May 15, 2013 at 20:29
  • None of these duplicates explain how a complex array is sorted Commented May 15, 2013 at 20:29
  • @jQuerybeast If by "complex array" you mean an array of dictionaries, that is exactly what the duplicate shows. In your case you would simply parse the strings in a.result.date and b.result.date into valid Date instances, then subtract their Unix times. Commented May 15, 2013 at 20:32
  • @Asad the duplicated question has no explanation on what goes on. Copy pasting is not learning. Commented May 15, 2013 at 20:37
  • @jQuerybeast The code is self explanatory. I've edited the answer to elaborate anyway. Commented May 15, 2013 at 20:45

1 Answer 1

24
function comp(a, b) {
    return new Date(a.result.date).getTime() - new Date(b.result.date).getTime();
}

your_array.sort(comp);

Just to extend @Karthikr's comment.

var result = [];

result.push({
  id: 'ID',
  result: {
    url: 'test',
    date: '15 May 2013, 6:40 pm'
  }
}, {
  id: 'ID',
  result: {
    url: 'test',
    date: '20 Dec 2012, 8:00 am'
  }
}, {
  id: 'ID',
  result: {
    url: 'test',
    date: '29 Jun 2012, 5:47 pm'
  }
});

function comp(a, b) {
  return new Date(a.result.date).getTime() - new Date(b.result.date).getTime();
}

result.sort(comp);

$('body').append(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

3 Comments

5* what an amazing solution! legend.
Hi, i need more help in this i want to sort data by descending order? how to sort it?
Just switch the a and b in the return line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.