I am facing an issue with sorting an array of objects by a date property using the lodash function orderBy. I have tried to sort it in both ascending and descending order.
var searchObj = [{id: 1, postDate: '2/24/2016 5:08 PM'},
{id: 2, postDate: '3/14/2012 8:39 AM'},
{id: 3, postDate: '3/23/2016 1:56 AM'},
{id: 4, postDate: '5/9/2016 8:14 AM'},
{id: 5, postDate: '11/11/2016 05:26 PM'},
{id: 6, postDate: '05/19/2016 03:40 AM'},
{id: 7, postDate: '5/10/2016 9:23 PM'},
{id: 8, postDate: '11/07/2017 01:07 PM'},
{id: 9, postDate: '6/7/2011 9:20 AM'},
{id: 10, postDate: '11/03/2015 12:03 PM'}];
console.log(searchObj);
searchObj = _.orderBy(searchObj, [obj =>
new Date(obj['postDate'].trim()).getTime() / 10000
], ['asc']);
console.log(searchObj);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b9bab1b4a6bd95e1fbe4e2fbe1">[email protected]</a>/lodash.min.js"></script>
However, the sorted array is not always correct, resulting in mixed up dates like:
- 2/24/2016 5:08 PM
- 3/14/2012 8:39 AM
- 3/23/2016 1:56 AM
- 5/9/216 8:14 AM
- 5/10/2016 9:23 PM
- 6/7/2011 9:20 AM
Does anyone have any suggestions on how to fix this sorting issue?