按周javascript分组日期

时间:2018-01-03 19:13:30

标签: javascript arrays date group-by

我有一系列波斯日期,我希望按周分组日期。 例如,我有以下数组:

[
    "1396-10-11 09:07:21",
    "1396-10-10 10:03:51",
    "1396-10-07 02:07:02",
    "1396-11-27 08:02:45",
    "1396-11-19 01:02:32",
    "1396-12-01 22:13:21",
    "1396-02-12 09:07:21",
    "1396-05-18 04:02:29",
    "1396-05-21 14:01:42",
    "1396-07-11 01:16:29"
]

我希望按周分组日期。

我写了以下代码,但效果不佳:

Array.prototype.groupBy = function(prop) {
  return this.reduce(function(groups, item) {
    var val = item[prop];
    groups[val] = groups[val] || [];
    groups[val].push(item);
    return groups;
  }, {});
}

const formatted = dates.map(elem => {
  return { 
    numberOfWeek: moment(elem.date, 'jYYYY-jMM-jDD').startOf('jMonth').jWeek(),
    date: moment(elem.date, 'jYYYY-jMM-jDD').format('jYYYY-jMM-jDD'), 
    score: elem.score 
  };
});

2 个答案:

答案 0 :(得分:7)

使用moment().week()获取一年中的周数,然后按其分组,这是一个有效的示例,我使用array.reduce创建一个新的对象,其日期按周编号分组:



var dates = [
  "1396-10-11 09:07:21",
  "1396-10-10 10:03:51",
  "1396-10-07 02:07:02",
  "1396-11-27 08:02:45",
  "1396-11-19 01:02:32",
  "1396-12-01 22:13:21",
  "1396-02-12 09:07:21",
  "1396-05-18 04:02:29",
  "1396-05-21 14:01:42",
  "1396-07-11 01:16:29"
];

var groups = dates.reduce( function (acc, date) {

  var yearWeek = moment(date).year()+'-'+moment(date).week();
  
  // check if the week number exists
  if (typeof acc[yearWeek] === 'undefined') {
    acc[yearWeek] = [];
  }
  
  acc[yearWeek].push(date);
  
  return acc;

}, {});

console.log(groups);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

使用Lodash实现此目的的另一种简单方法如下:

const groupBy = require('lodash/groupBy');
const moment = require('moment');
const data = [
   "1396-10-11 09:07:21",
   "1396-10-10 10:03:51",
   "1396-10-07 02:07:02",
   "1396-11-27 08:02:45",
   "1396-11-19 01:02:32",
   "1396-12-01 22:13:21",
   "1396-02-12 09:07:21",
   "1396-05-18 04:02:29",
   "1396-05-21 14:01:42",
   "1396-07-11 01:16:29"
];

groupBy(data, (dt) => moment(dt).week());

结果如下:

{ 
  '7': [ '1396-02-12 09:07:21' ],
  '21': [ '1396-05-18 04:02:29', '1396-05-21 14:01:42' ],
  '29': [ '1396-07-11 01:16:29' ],
  '41': [ '1396-10-07 02:07:02' ],
  '42': [ '1396-10-11 09:07:21', '1396-10-10 10:03:51' ],
  '47': [ '1396-11-19 01:02:32' ],
  '49': [ '1396-11-27 08:02:45', '1396-12-01 22:13:21' ] 
}