使用 Map-reduce。这是一个使用 underscore.js 的示例。虽然有点冗长,但它非常简单。
var data = [{
"USER_NAME": "User1",
"LAST_SUCCESSFUL_CONNECT": "1373978337642"
}, {
"USER_NAME": "User2",
"LAST_SUCCESSFUL_CONNECT": "1374515704026"
}, {
"USER_NAME": "User3",
"LAST_SUCCESSFUL_CONNECT": "1374749782479"
}, {
"USER_NAME": "User4",
"LAST_SUCCESSFUL_CONNECT": "1274749702479"
}];
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var map_result = _.map(data, function (item) {
var d = new Date(new Number(item.LAST_SUCCESSFUL_CONNECT));
var month = monthNames[d.getMonth()] + ", " + d.getFullYear();
return {
"Month": month,
"User_Count": 1
};
});
var result_temp = _.reduce(map_result, function (memo, item) {
if (memo[item.Month] === undefined) {
memo[item.Month] = item.User_Count;
}else{
memo[item.Month] += item.User_Count;
}
return memo;
},{});
//then wrap the result to the format you expected.
var result = _.map(result_temp, function(value, key){
return {
"Month": key,
"User_Count": value
};
});
console.log(result);