我有一个对象数组,其中每个对象都有一个日期属性。我想将具有相同日期的所有对象移动到一个数组中,并创建与不同日期值一样多的数组。迭代数组并对数组进行排序的最佳方法是什么?使用 Angular 数组函数就可以了。
最佳答案
我会混合使用 orderby $filter 和简单的 for 数组。 让我们通过一个例子来看看:
//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]);
关于javascript - 根据日期属性对 javascript 对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39318194/