I have an array of objects that include a startDate. The objects are not in order of startDate. I want to create a new array and group all objects that share the same startDate into separate objects.
var eventArray = [
{
eventName: "event1",
startDate: "2018/08/01", // YYYY/MM/DD
id: 1
},
{
eventName: "event2",
startDate: "2018/08/03",
id: 2
},
{
eventName: "event3",
startDate: "2018/08/01",
id: 3
},
{
eventName: "event4",
startDate: "2018/08/06",
id: 4
}
];
Using angular.forEach I've tried looping through all the objects, getting the startDate value, adding that value to a new array, and adding the current object to the array where it has a matching date. I cannot find a solution to add the current event object to the object that exists in the new array (eventDays) at the index that matches my eventIndex variable.
let eventDays = [];
let eventIndex = 0;
angular.forEach(eventArray, function(event){
let day = event.startDate;
if(eventDays.length == 0){
eventDays.push({
dateGroup: day,
event
});
}
else {
if(event.startDate == eventDays[eventIndex].groupDay) {
// insert event object into eventDays[eventIndex] after dateGroup, event
}
else if(event.startDate !== eventDays[eventIndex].groupDay){
eventDays.push({
dateGroup: day,
event
});
eventIndex++;
}
}
});
The result I'm looking for is something like this.
eventDays = [
{
groupDate: "2018/08/01",
event: {
eventName: "event1",
startDate: "2018/08/01",
id: 1
},
event: {
eventName: "event3",
startDate: "2018/08/01",
id: 3
}
},
{
groupDate: "2018/08/03",
event: {
eventName: "event2",
startDate: "2018/08/03",
id: 2
}
},
{
groupDate: "2018/08/06",
event: {
eventName: "event4",
startDate: "2018/08/06",
id: 4
}
}
];
Is something like this possible?
UPDATE
Nina is right, I cannot reuse the name keyname. I need to create another array within the object to store the objects I'm passing over. This snippet is working.
angular.forEach($scope.events, function (event) {
if ($scope.eventDays.length == 0) {
$scope.eventDays.push({
'groupDate': event.startDate,
'events': [event]
});
} else {
if (event.startDate == $scope.eventDays[eventIndex].groupDate) {
$scope.eventDays[eventIndex].events.push(event)
} else if (event.startDate !== $scope.eventDays[eventIndex].groupDate) {
$scope.eventDays.push({
'groupDate': event.startDate,
'events': [event]
});
eventIndex++;
}
}
});
event. You have to think about any other output alternative. When you do so, update the question.eventto aneventsarray. This is working!