Flutter/Dart how to groupBy list of maps

extension UtilListExtension on List{
  groupBy(String key) {
    try {
      List<Map<String, dynamic>> result = [];
      List<String> keys = [];

      this.forEach((f) => keys.add(f[key]));

      [...keys.toSet()].forEach((k) {
        List data = [...this.where((e) => e[key] == k)];
        result.add({k: data});
      });

      return result;
    } catch (e, s) {
      printCatchNReport(e, s);
      return this;
    }
  }
}

then use it like this

var data = [
    {"title": 'Avengers', "release_date": '10/01/2019'},
    {"title": 'Creed', "release_date": '10/01/2019'},
    {"title": 'Jumanji', "release_date": '30/10/2019'},
];

var result = data.groupBy('title');
print(result);

then the result is

[{10/01/2019: [{title: Avengers, release_date: 10/01/2019}, {title: Creed, release_date: 10/01/2019}]}, {30/10/2019: [{title: Jumanji, release_date: 30/10/2019}]}]

The package collection implements the groupBy function.

For grouping by date:

import "package:collection/collection.dart";

main(List<String> args) {
  var data = [
    {"title": 'Avengers', "release_date": '10/01/2019'},
    {"title": 'Creed', "release_date": '10/01/2019'},
    {"title": 'Jumanji', "release_date": '30/10/2019'},
  ];


  var newMap = groupBy(data, (Map obj) => obj['release_date']);

  print(newMap);
}

For removing the release_date key from each map entry:

var newMap = groupBy(data, (Map obj) => obj['release_date']).map(
    (k, v) => MapEntry(k, v.map((item) { item.remove('release_date'); return item;}).toList()));

For changing a key:

var newMap = groupBy(data, (Map obj) => obj['release_date']).map(
    (k, v) => MapEntry(k, v.map((item) => {'name': item['title']}).toList()));

If you have Dart 2.7, you can extend Iterable to add a useful groupBy method:

extension Iterables<E> on Iterable<E> {
  Map<K, List<E>> groupBy<K>(K Function(E) keyFunction) => fold(
      <K, List<E>>{},
      (Map<K, List<E>> map, E element) =>
          map..putIfAbsent(keyFunction(element), () => <E>[]).add(element));
}

Now, you're List of Maps, could be grouped using something like:

final releaseDateMap = listOfMaps.groupBy((m) => m['release_date'])

Data like this:

[
    {title: 'Avengers', release_date: '10/01/2019'},
    {title: 'Creed', release_date: '10/01/2019'}
    {title: 'Jumanji', release_date: '30/10/2019'},
]

would turn into:

{
  '10/01/2019': [
    {title: 'Avengers', release_date: '10/01/2019'},
    {title: 'Creed', release_date: '10/01/2019'}
  ],
  '30/10/2019': [
    {title: 'Jumanji', release_date: '30/10/2019'},
  ]
}

Tags:

Dart

Flutter