javascript - How can I group an array of objects by month? -


i'm using javascript. have array contains data in format:

[         {"user_name":"user1","last_successful_connect":"1373978337642"},         {"user_name":"user2","last_successful_connect":"1374515704026"},         {"user_name":"user3","last_successful_connect":"1374749782479"} ] 

(the numbers above represent utc date/time in milliseconds.

i group (count) data month. this:

[     {"month":"january, 2014","user_count": 2},     {"month":"february, 2014","user_count": 1}, ] 

i use jquery if simplifies matters.

this looks map reduce problem. high-level solution follows:

  1. re-organize members of list.
  2. count them.

here step-by-step how-to achieving this:

map

  1. iterate through list of dictionaries
  2. convert datetime string javascript datetime object.
  3. use month-year key , list of dictionaries value.

these grouped month-year.

example:

var l = [...]; var o = {}; var f = function(x){     var dt_object = date(x["last_successful_connect"]); // convert datetime object     var key = dt_object.year + '-' + dt_object.month;      if (o[key] === undefined) {         var o[key] = [];     };      o[key].push(x) }  _.map(l, f(x)) //apply f each member of l 

reduce

  1. iterate through new object containing dictionaries of lists.
  2. calculate length of each dictionary's list.
  3. use count key , length of list value.

example:

var g = function(member_count){     //extra logic may go here     return member_count }  member in o {     count = _.reduce(l, g(member))     member['count'] = count } 

resulting api

o['month-year'] //for list of dictionaries in month o['month-year']['count'] //for count of list of dictionaries in month. 

references:

for map , reduce functions in javascript see underscore.js:
http://underscorejs.org/#map
http://underscorejs.org/#reduce

javascript date object:
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/date

for more information on date , datetime objects:
https://en.wikipedia.org/wiki/iso_8601

for more information on map reduce:
https://en.wikipedia.org/wiki/mapreduce


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -