Abhishek Pandey Abhishek Pandey - 4 months ago 16
Javascript Question

Sort javascript object based on a date property

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.


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 = {};
   if(dictionary[object.date] == undefined)
      dictionary[object.date] = [];


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

see $filter and orderby documentation to see how you can order it by a object property