Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort JSON array by date key [duplicate]

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

like image 461
jQuerybeast Avatar asked Sep 17 '26 02:09

jQuerybeast


1 Answers

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>
like image 123
gongzhitaao Avatar answered Sep 18 '26 16:09

gongzhitaao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!