javascript - JS: Get objects from array within a time range -


there object array this:

[   {     timestamp: 1318781876     any: 'other fields'   } ] 

of course there multiple objects in array. using momentjs - if matters here...

now need split array months. means need objects 'july' display them in table. possible @ or should change datastructure? thought using timestamp best option, calculate this.

but i'm thinking if have add month , year field object...

you iterate array , build tree, may write year , month objects:

var map={};  array.foreach(function(obj){  var d = new date(obj.timestamp*1000);  var m = obj.month = d.getmonth() +1;  var y = obj.year = d.getfullyear();    if(!map[y]) map[y]={};   if(!map[y][m]) map[y][m]=[];    map[y][m].push(obj); }); 

so weve got map this:

map: {   2017 : {    8 : [     {       timestamp:123456,       month:8,       year:2017,       any:"other value"     }   ] } } 

so can julys by:

map[2017][7] 

it depends if once, other answers easier, if need different timeranges upper code needs iterate once, , can filtered results easily. sorted results:

var sorted=object.keys(map)/*the years*/ .sort().map(function(year){   return { year, months: object.keys(map[year]).sort().map(function(month){     return {month,results:map[year][month]};   })  }; }); 

these arrays may built while building hash table, see ninas way of doing this


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -