简体   繁体   English

根据日期属性对JavaScript对象进行排序

[英]Sort javascript object based on a date property

I have an array of objects in which each object has a date property. 我有一个对象数组,其中每个对象都有一个date属性。 I want to move all the objects having the same date to an array and make as many arrays as the different date values. 我想将所有具有相同日期的对象移到一个数组中,并制作与不同日期值一样多的数组。 What would be the best way to iterate over the array and sort this array. 遍历数组并对数组进行排序的最佳方法是什么。 Using angular array functions is fine. 使用角度数组函数很好。

I would do a mix of orderby $filter and a simple for array. 我会混合使用orderby $ filter和一个简单的array。 Let's see it by an example: 让我们看一个例子:

//example values..
var objects = [{exampleProp: undefined, date:new Date(3,1,1970) }, 
              {exampleProp: undefined, date:new Date(2,1,1970)}, 
              {exampleProp: undefined, date:new Date(2,1,1970)}, 
              {exampleProp: undefined, date:new Date(1,1,1970)}];


//ordering your master array by date property..
objects = $filter('orderBy', objects, 'date')($scope);

//grouping by date your master object..
var dictionary = {};
objects.forEach(function(object){
   if(dictionary[object.date] == undefined)
      dictionary[object.date] = [];

    dictionary[object.date].push(object);
});

//transforming your dictionary to an array of array....
var objectsByDate = [];
for(var date in dictionary)
  objectsByDate.push(dictionary[date]);

see $filter and orderby documentation to see how you can order it by a object property 请参阅$ filterorderby文档,以了解如何通过对象属性对其进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM