javascript - Sorting an array by date - Stack Overflow

How do you sort the following sample array by the dt (date) property of each object?$scope.arr = [ {tes

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 plicated things as my real code is more plex.

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

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 plicated things as my real code is more plex.

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

Share Improve this question asked Aug 9, 2016 at 16:40 propro 7927 silver badges31 bronze badges 6
  • I think it's a duplicate of this, but I'll reopen it as it's not really sorting "by strings", but by dates. Maybe someone else has a more appropriate duplicate, because this has surely been asked before. – adeneo Commented Aug 9, 2016 at 16:43
  • Anyway, you have to parse the dates to valid date objects, and then just do $scope.arr.sort( (a,b) => { return parse(a) - parse(b) }); etc. – adeneo Commented Aug 9, 2016 at 16:44
  • can you convert to ints and then pare? Date.parse("March 21, 2012"); – brad Commented Aug 9, 2016 at 16:45
  • stackoverflow./questions/10238127/… ? That answer suggests creating a sort function and converting the string to a date. – Jason P Commented Aug 9, 2016 at 16:45
  • The best thing you can do is create and array of months using keys as numbers and use that to pare with the array you have above. – Robert Commented Aug 9, 2016 at 16:46
 |  Show 1 more ment

5 Answers 5

Reset to default 6

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

$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);

Suffice it to sort on the second property casted as a Date Object :

var 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'}
];

arr.sort((a,b) => new Date(b.dt) - new Date(a.dt));
console.log(arr);

As those aren't really valid dates, even if they can be parsed by some browser, you'd generally want to parse them properly and pass in numbers to new Date, then sort based on the date objects etc.

var months = [
  'January',
  'February',
  'March',
  'April',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

function parse(dt) {
  var p = dt.replace(/(\,|\:)/g, ' ').split(/\s+/).filter((x) => {
    return x.trim().length > 0;
  });
  return new Date(p[2], months.indexOf(p[0]), p[1], p[3], p[4], p[5]);
}
var $scope = {}; // for demonstration ...

$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) => {
  return parse(b.dt) - parse(a.dt);
});

document.body.innerHTML = '<pre>' + JSON.stringify($scope.arr, 0, 4) + '</pre>';

You can solve it via multiple ways. Either you change the format of the date to get back something like "YYYY-MM-DDThh:mm:ss.sTZD" and then use orderBy to leverage the angular order by. Else you can loop and sort it manually with use of moment library.

Something like this

angular.forEach($scope.arr, function(o){ o.dt = new Date(o.dt); });

and then user orderBy for sorting.

A bination of Angular Custom Filter and the orderBy filter can achieve this. This will also allow for further custom formatting.

Updated: Now shows adding new dates and ordering by any field.

angular.module("app", ['core']);

angular.module("app").controller("TestCtrl", function($scope) {

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

  $scope.addDate = function() {
    var lastIndex = $scope.arr[$scope.arr.length - 1].test;
    $scope.arr.push({
      test: lastIndex + 1,
      dt: new Date($scope.newDate)
    });
  }

});

angular.module("core", []);
angular.module("core").filter("format", function(dateFilter) {
  return function(input) {
    if (input instanceof Date)
      return dateFilter(input, 'medium');
    return input;
  };
});
<script src="https://ajax.googleapis./ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<body ng-app="app">
  <div ng-controller="TestCtrl">
    <input type="text" ng-model="newDate">
    <button ng-click="addDate()">Add Date</button>
    <br/>OrderBy Field:
    <input type="text" ng-model="orderField">

    <table>
      <thead>
        <th ng-repeat="(key,val) in arr[0]">
          {{key}}
        </th>
      </thead>
      <tbody>
        <tr ng-repeat="o in arr | orderBy:orderField">
          <td ng-repeat="(key,val) in o">{{val | format}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744269408a4566026.html

相关推荐

  • javascript - Sorting an array by date - Stack Overflow

    How do you sort the following sample array by the dt (date) property of each object?$scope.arr = [ {tes

    7天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信