Elwyn Elwyn - 26 days ago 10
AngularJS Question

Using lodash to prepare data for "last day user registration" chart

I want to use lodash to prepare data for "last day user registration" chart.

Here is my users array:

{
name: toto,
creationDate: 11/11/2016 11:00:00
},
{
name: tata,
creationDate: 11/11/2016 10:00:00
}


I need to create a chart with ChartJS that repesent the users registrations over th last day (24 hours).

If I use groupBy :

var grouped = _.groupBy(users, function (user) {
return moment(user.creationDate).get('hour');
});


I can't have the "empty" hours, when there is no user registration, in the final array.

The aim is to have this :

labels = ['18', '17', '16', ... '18']
data = [['1', '1', '12, ... '3']]


Could you please help ?

Answer

Use _.countBy() to count the registrations per hour. Then use _.range() to create an array of hours, you'll map into pairs of [hour, registration], and transpose the arrays by applying _.zip():

function countHours(arr, start) {
  var registrations = _.countBy(arr, function(user) {
    return moment(user.creationDate).get('hour');
  });

  return _.zip.apply(_, _.range(start, start + 24).map(function(hour) {
    var h = hour % 24;
    return [h, registrations[h] || 0];
  }));
}

var arr = [{
  name: "toto",
  creationDate: "11/11/2016 11:00:00"
}, {
  name: "tata",
  creationDate: "11/11/2016 10:00:00"
}, {
  name: "toto",
  creationDate: "11/11/2016 11:00:00"
}, {
  name: "tata",
  creationDate: "11/11/2016 11:00:00"
}, {
  name: "toto",
  creationDate: "11/11/2016 12:00:00"
}, {
  name: "tata",
  creationDate: "11/11/2016 10:00:00"
}, {
  name: "toto",
  creationDate: "11/11/2016 11:00:00"
}, {
  name: "tata",
  creationDate: "11/11/2016 10:00:00"
}, {
  name: "toto",
  creationDate: "11/11/2016 11:00:00"
}, {
  name: "tata",
  creationDate: "11/11/2016 11:00:00"
}, {
  name: "toto",
  creationDate: "11/11/2016 12:00:00"
}, {
  name: "tata",
  creationDate: "11/11/2016 10:00:00"
}];

var usage = _.countBy(arr, function(user) {
  return moment(user.creationDate).get('hour');
});

var result = countHours(arr, 12);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>