想要简单解决就用 lodash 库
var _=require('lodash');
var arr=[{
"id": 1,
"flightDate": "2016-05-11"
}, {
"id": 2,
"flightDate": "2016-05-10"
}, {
"id": 3,
"flightDate": "2016-03-09"
}, {
"id": 4,
"flightDate": "2016-04-08"
}, {
"id": 5,
"flightDate": "2016-04-07"
}];
var re=_.groupBy(arr,function(item){
return (new Date(item.flightDate).getMonth());
})
console.log(re);
输出结果:
{ '2': [ { id: 3, flightDate: '2016-03-09' } ],
'3':
[ { id: 4, flightDate: '2016-04-08' },
{ id: 5, flightDate: '2016-04-07' } ],
'4':
[ { id: 1, flightDate: '2016-05-11' },
{ id: 2, flightDate: '2016-05-10' } ] }
现在才看到楼主要原生的实现方法,也可以,
我写一个
var dd = {};
var getM = function (item){
return (new Date(item.flightDate).getMonth());
}
arr.forEach(function(value,key){
var keys=getM(value);
if(Object.prototype.hasOwnProperty.call(dd,keys)){
dd[keys].push(value);
} else
{
dd[keys] = [value];
}
})
console.log(dd);