skip to Main Content

I have this Group object

class Group {
      final String dateFormatted;
      final List<Event> events;
    
      Group({required this.dateFormatted, required this.events});
    }

I need to fold the group so that all Groups with common dateFormatted will be merged into the same group and create a new Group Object with that data.

I have the following issue on screen with the current structure

enter image description here

2

Answers


  1. Here how you can group common date events

    List<Group> mergeGroups(List<Group> groups) {
    
    
    // Create a map to group events by dateFormatted
      final Map<String, List<Event>> groupedEvents = {};
    
      for (var group in groups) {
        if (!groupedEvents.containsKey(group.dateFormatted)) {
          groupedEvents[group.dateFormatted] = [];
        }
        groupedEvents[group.dateFormatted]!.addAll(group.events);
      }
    
      // Convert the map back to a list of Group objects
      return groupedEvents.entries
          .map((entry) => Group(dateFormatted: entry.key, events: entry.value))
          .toList();
    }
    
    Login or Signup to reply.
  2. List<Group> mergedGroups(List<Group> seperateGroups) {
      List<Group> mergedGroups = [];
      for (var group in seperateGroups) {
        Group isExistingGroup = mergedGroups.firstWhere(
          (g) => g.dateFormatted == group.dateFormatted,
          orElse: () => null,
        );
    
        if (isExistingGroup != null) {
     isExistingGroup.events.addAll(group.events);
        } else {
          
          mergedGroups.add(Group(
            dateFormatted: group.dateFormatted,
            events: group.events.toList(),
          ));
        }
      }
    
      return mergedGroups;
    }
    

    This might work. You want to combine a list of group object. Here you pass groups to the function as parameter and it checks whether a group exists with formattedDate or not. If exists, add events to that group else it creates a group. (If your formattedDate has hour:min:s:ms values it does not work. Be sure formattedDate has only year/month/day values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search