每天计算元素Javascript

时间:2017-05-31 18:13:19

标签: javascript counting

我有像下面这样的对象数组。

<select [(ngModel)]="todo.priority" name="priority" >
  <option *ngFor="let priority of formModel.priorities" [ngValue]="priority">
      {{priority.name}}
  </option>
</select>

我想计算每天有多少个对象并创建一个这样的数组: [ { name: 'order-1', date: '2017-05-30 16:38:30.418Z' }, { name: 'order-2', date: '2017-05-30 16:38:30.418Z' }, { name: 'order-3', date: '2017-05-31 16:38:30.418Z' } ]

我能够使用underscore.js和时刻库

按天分组记录
[1, 2]

我如何计算下面的元素?

_.groupBy(orders, function order) {
  return moment(order.created).startOf('day').format();
});

3 个答案:

答案 0 :(得分:1)

也许是这样的:

var orders = [
    {
        name: 'order-1',
        date: '2017-05-30 16:38:30.418Z'
    },
    {
        name: 'order-2',
        date: '2017-05-30 16:38:30.418Z'
    },
    {
        name: 'order-3',
        date: '2017-05-31 16:38:30.418Z'
    }
];
var res = _.chain(orders)
.groupBy(function(order) {
    return moment(order.date).startOf('day').format();
})
.map(function(obj){
    return obj.length;
})
.value();


console.log(res); //[ 2, 1 ]

编辑: 使用_优于.reduce()的优势在于它(稍微)更具可读性,结果是请求的格式。

答案 1 :(得分:1)

您可以使用.reduce()函数计算给定日期的出现次数,如下所示:

使用.reduce()优于_.groupBy().map()的优势在于,您只需对您的数据集进行一次迭代,从而使其(稍微)更高效。

&#13;
&#13;
var orders = [
  {
    name: 'order-1',
    date: '2017-05-30 16:38:30.418Z'
  },
  {
    name: 'order-2',
    date: '2017-05-30 16:38:30.418Z'
  },
  {
    name: 'order-3',
    date: '2017-05-31 16:38:30.418Z'
  }
];

dayCounts = orders.reduce(function (result, order) {
    var day = moment(order.date).format("YYYY-MM-DD");
    if (!result[day]) {
        result[day] = 0;
    }
    result[day]++;
    return result;
}, {});

console.log(dayCounts);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

你可以这样做:

var orders = [
  {
    name: 'order-1',
    date: '2017-05-30 16:38:30.418Z'
  },
  {
    name: 'order-2',
    date: '2017-05-30 16:38:30.418Z'
  },
  {
    name: 'order-3',
    date: '2017-05-31 16:38:30.418Z'
  }
];

var res = [];

orders.forEach(function (elem) {
    var date = elem.date.split(' ')[0];


    if (res[date]) {
        res[date] += 1;
    } else {
        res[date] = 1;
    }
});

console.log(res); // [2017-05-30: 2, 2017-05-31: 1]