Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  168] [ 5]  / answers: 1 / hits: 26492  / 11 Years ago, wed, may 15, 2013, 12:00:00

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


More From » arrays

 Answers
8
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>




[#78213] Tuesday, May 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maureen

Total Points: 151
Total Questions: 110
Total Answers: 110

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
;