I have an array-snapshot out of Firebase, which contains the entries of my application. Among other information there is a a timestamp called "referenceDate":
entry [0] { referenceDate: 2017-08-03,...
entry [1] { referenceDate: 2017-08-02,...
entry [2] { referenceDate: 2017-08-01,...
entry [3] { referenceDate: 2017-07-03,...
entry [4] { referenceDate: 2017-07-02,...
I want to output the entries grouped under a headline by month and year like this
08.2017
03.08.2017
02.08.2017
01.08.2018
07.2017
03.07.2017
02.07.2017
My idea is to loop over the array-snapshot and create another nested one which looks like this:
{"monthYear": "08.2017":[
{"referenzDatum": 2017-08-03},... },
{"referenzDatum": 2017-08-02},... },
{"referenzDatum": 2017-08-01},... },]},
{"monthYear": "07.2017":[
{"referenzDatum": 2017-07-03},... },
{"referenzDatum": 2017-07-02},... }, ...]}
Then loop over it with two nested ngFor to generate the html output.
Is there a simple way to achieve this? I tried to just push the old entry into the new array according to the corresponding monthyear whenever this changes, but that didnt work out, because references were copied. then I tried the following code, but it doesn't really work for more than 2 different months and the code just looks awful.
var oldDate: string;
var newDate: string;
sortedLogLine.entries = [];
this.sortedLog = [];
for (var i = 0; i < entries.length; i++) {
newDate = entries[i].referenceDate.substring(0, 7).split('-').reverse().join('.');
if (oldDate == newDate) {
sortedLogLine.entries.push(entries[i]);
}
if (!oldDate) {
sortedLogLine.entries.push(entries[i]);
sortedLogLine.monthYear = newDate;
oldDate = newDate;
}
if (oldDate != newDate) {
pushSortedLogLine.entries = sortedLogLine.entries.slice(0);
pushSortedLogLine.monthYear = oldDate;
this.sortedLog.push(pushSortedLogLine);
sortedLogLine.entries = [];
sortedLogLine.entries.push(entries[i]);
sortedLogLine.monthYear = newDate;
oldDate = newDate;
}
}
this.sortedLog.push(sortedLogLine);
Any suggestions as to how to do this more efficiently?