Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

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

I'm using JavaScript. I have an array that contains data in this 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 would like to group (count) the data by month. Something like this:

[
    {"Month":"January, 2014","User_Count": 2},
    {"Month":"February, 2014","User_Count": 1},
]

I could use jQuery if it simplifies matters.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This looks like a map reduce problem. The high-level solution is as follows:

  1. Re-organize the members of the list.
  2. Count them.

Here is a step-by-step how-to for achieving this:

Map

  1. Iterate through the list of dictionaries
  2. Convert datetime string to javascript datetime object.
  3. Use month-year as key and list of dictionaries as value.

These are now grouped by month-year.

Example:

var l = [...];
var o = {};
var f = function(x){
    var dt_object = Date(x["LAST_SUCCESSFUL_CONNECT"]); // convert to 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 to each member of l

Reduce

  1. Iterate through the new object containing dictionaries of lists.
  2. Calculate length of each dictionary's list.
  3. Use count as key and length of list as its value.

Example:

var g = function(member_count){
    //extra logic may go here
    return member_count
}

for member in o {
    count = _.reduce(l, g(member))
    member['count'] = count
}

Resulting API

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

References:

For map and 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 and DateTime objects:
https://en.wikipedia.org/wiki/ISO_8601

For more information on map reduce:
https://en.wikipedia.org/wiki/MapReduce


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...