I have an array of objects in which each object has a date property. 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.
Asked
Active
Viewed 286 times
1 Answers
1
I would do a mix of orderby $filter and a simple for 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

Abhishek Pandey
- 300
- 1
- 13

illeb
- 2,942
- 1
- 21
- 35
-
Just curious, is there any difference here in using `==` instead of `===` for `if(dictionary[object.date) == undefined`? I am honestly curious because I tend to use `===`. – Mdd Sep 04 '16 at 15:50
-
1In moist of the cases, they are just equal. == is *a little* slower than === because no type conversion is needed. For a very good in-depth overview, see this post http://stackoverflow.com/a/359509/1306679 – illeb Sep 04 '16 at 15:55