首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有唯一DateTime字符串的数组?

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

Stack Overflow用户
提问于 2017-11-07 11:56:50
回答 2查看 163关注 0票数 1

我有Array<object>,它包含类型为n的对象

代码语言:javascript
复制
{
  name: 'random',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-23 11:00'
}

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

EN

回答 2

Stack Overflow用户

发布于 2017-11-07 12:01:34

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

代码语言:javascript
复制
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);
代码语言:javascript
复制
.as-console-wrapper { max-height: 100% !important; top: 0; }

票数 1
EN

Stack Overflow用户

发布于 2017-11-07 13:42:15

代码语言:javascript
复制
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);
代码语言:javascript
复制
.as-console-wrapper { max-height: 100%!important; top: 0; }

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47157390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档