Sort JSON array by date key
24,995
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>
Comments
-
jQuerybeast almost 4 years
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