【问题标题】:Array with unique DateTime strings? [duplicate]具有唯一日期时间字符串的数组? [复制]
【发布时间】:2017-11-07 11:56:50
【问题描述】:

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

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

我想要的是,在渲染结果之前,在 new Array<object 中过滤这个数组,其中包含 startDate (并且它的唯一性,2017-11-10 09:002017-11-10 10:00 不是唯一的)和counter 这个Date 在数据数组中出现了多少次。我怎样才能做到这一点?

【问题讨论】:

  • 它是 Angular 的吗?你有 Lodash 吗?
  • 好吧,如果一个人仔细阅读了 OP 的问题,并用将 Q 标记为“重复”的链接答案对它进行了复核,那么清楚地看到那里的任何方法都不起作用,因为 OP 要求一个计数器项目列表,每个项目都包含最初提供的日期列表中的唯一开始日期,以及该原始列表中唯一开始日期的总计数。因此,请从“重复”中取消标记此 Q,除非 社区 提供了一个新的“重复”链接来解决 OP 的问题。
  • @PeterSeliger 我已投票重新提出这个问题。我完全同意你的看法。感谢 cmets

标签: javascript typescript


【解决方案1】:

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);
.as-console-wrapper { max-height: 100%!important; top: 0; }

【讨论】:

    【解决方案2】:

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

    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);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      • 2019-03-31
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多