具有唯一DateTime字符串的数组?

时间:2017-11-07 11:56:50

标签: javascript typescript

我有Array<object>,其中包含<{p>类型的n个对象

{
  name: 'random',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-23 11:00'
}

我想要的是,在渲染结果之前,在 Array<object中过滤此数组,其中包含startDate(及其唯一的2017-11-10 09:00和{ {1}}不是uniques)和2017-11-10 10:00这个counter在数据数组中的次数。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以先使用Array.prototype.reduce()这样:

&#13;
&#13;
const dates = [{
    name: 'random',
    startDate: '2017-11-10 09:00',
    endDate: '2017-11-23 11:00'
  },
  {
    name: 'random',
    startDate: '2017-11-10 09:00',
    endDate: '2017-11-23 11:00'
  },
  {
    name: 'random',
    startDate: '2017-11-10 09:00',
    endDate: '2017-11-23 11:00'
  },
  {
    name: 'random',
    startDate: '2017-08-12 09:00',
    endDate: '2017-11-23 11:00'
  }
];

const hash = dates.reduce((a, c) => (a[c.startDate] = ++a[c.startDate] || 1, a), {});
const uniqueDates = Object.keys(hash).map(k => ({ startDate: k, counter: hash[k] }));

console.log(uniqueDates);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
var dateList = [{
  name: 'foo',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-23 11:00'
}, {
  name: 'bar',
  startDate: '2017-11-10 09:01',
  endDate: '2017-11-23 11:00'
}, {
  name: 'baz',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-24 10:00'
}, {
  name: 'biz',
  startDate: '2017-11-10 09:01',
  endDate: '2017-11-25 09:00'
}, {
  name: 'quick',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-23 11:00'
}, {
  name: 'brown',
  startDate: '2017-12-10 09:00',
  endDate: '2017-11-23 11:00'
}, {
  name: 'fox',
  startDate: '2017-12-10 10:00',
  endDate: '2017-11-23 11:00'
}];


var startDateCountList = dateList.reduce(function (collector, dateItem) {
  var
    startDate = dateItem.startDate,
    dateCount = collector.registry[startDate];

  if (!dateCount) {
    dateCount = collector.registry[startDate] = {
      startDate : dateItem.startDate,
      count     : 0
    };
    collector.list.push(dateCount);
  }
  dateCount.count += 1;

  return collector;

}, {

  registry: {},
  list:     []

}).list;


console.log('startDateCountList : ', startDateCountList);
&#13;
.as-console-wrapper { max-height: 100%!important; top: 0; }
&#13;
&#13;
&#13;