0

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 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.