2

I have an array of an objects with different TimeStamps, which are Moment-Objects from MomentJS.

 [
  {
    "name": "A",
    "eventDateTime": "2016-12-09 07:50:17",
  },
  {
    "name": "B",
    "eventDateTime": "2016-12-09 06:50:17",
  },
  {
    "name": "C",
    "eventDateTime": "2016-12-09 07:01:17",
  }
]

Now what I need to do (There are normally more of these objects) is to first sort them and then group then by a 15 minute Interval.

So sorted I should get

[
  {
    "name": "B",
    "eventDateTime": "2016-12-09 06:50:17",
  },
  {
    "name": "C",
    "eventDateTime": "2016-12-09 07:01:17",
  },
  {
    "name": "A",
    "eventDateTime": "2016-12-09 07:50:17",
  }]

And then I need to group them starting with The first object with the Time 06:50:17. So this will be my first group where all objects should be added, which are between 06:50:17 and 07:05:17. Since the array is sorted I can just iterate until one object is older than 07:05:17.

All in all it's not hard to realize, however it should be as efficient as possible. We use Lodash.js which has many functionalities. I know of the groupBy Method, however not how to A) use MomentJS and B) Define a function inside it, which checks for intervals.

Do you guys have some tips?

user5417542
  • 3,146
  • 6
  • 29
  • 50

1 Answers1

2

var data = [{
  "name": "A",
  "eventDateTime": "2016-12-09 07:50:17",
}, {
  "name": "B",
  "eventDateTime": "2016-12-09 06:50:17",
}, {
  "name": "C",
  "eventDateTime": "2016-12-09 07:01:17",
}];
var sortedDate = _.sortBy(data, function(o) {
  return o.eventDateTime;
});

var groupTime = null; // new Date(new Date(sortedData[0].eventDateTime).getTime() + 15 * 60000);
var groupedData = _.groupBy(sortedDate, function(d) {
  // no need to do this if eventDateTime is already a Date object
  var time = new Date(d.eventDateTime);
  // you can remove this condition and initialize groupTime with [0].eventDateTime
  if (!groupTime) groupTime = new Date(time.getTime() + 15 * 60000);
  return time - groupTime <= 900000 ? groupTime : groupTime = time;
});

// modify the groupedData keys however u want
console.log(groupedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
Ja9ad335h
  • 4,995
  • 2
  • 21
  • 29