pro pro - 3 months ago 7
Javascript Question

Sorting an array by date

How do you sort the following sample array by the dt (date) property of each object?

$scope.arr = [
{test: 1, dt: 'March, 10 2016 14:55:00'},
{test: 2, dt: 'February, 10 2013 14:25:00'},
{test: 3, dt: 'August, 10 2015 14:55:00'}
];


I tried _.sortBy($scope.arr, 'dt'), but that treats the date as a string and only does the sorting alphabetically. I tried converting the date into unix time and that actually complicated things as my real code is more complex.

Do you have any other suggestions of sorting the above in a descending order and show the result in a dropdown?

Answer

You can sort with this call back which uses the Date equivalents for comparing:

$scope.arr.sort( (a, b) => new Date(a.dt) - new Date(b.dt) );

$scope = {}; // for the snippet to work
$scope.arr = [ 
    {test: 1, dt: 'March, 10 2016 14:55:00'},
    {test: 2, dt: 'February, 10 2013 14:25:00'},
    {test: 3, dt: 'August, 10 2015 14:55:00'} 
];

$scope.arr.sort( (a, b) => new Date(a.dt) - new Date(b.dt) );

console.log($scope.arr);

Comments