Flutter/Dart how to groupBy list of maps

dart map to list
flutter list groupby
dart map flutter
dart filter list
flutter dart map foreach
dart map entries
dart sorted list
flutter copy list

I have this list of maps.

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

I would like to write a code that would group the list of movies by release_date like that.

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

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, (obj) => obj['release_date']);

  print(newMap);
}

For removing the release_date key from each map entry:

var newMap = groupBy(data, (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, (obj) => obj['release_date']).map(
    (k, v) => MapEntry(k, v.map((item) => {'name': item['title']}).toList()));

groupBy function - collection library - Dart API, Map<T, List<S>> groupBy <S, T>(. Iterable<S> values,; T key(. S element. ) ) Groups the elements in values by the value returned by key . Returns a map from​  I have this list of maps. [ {title: 'Avengers', release_date: '10/01/2019'}, {title: 'Creed', release_date: '10/01/2019'} {title: 'Jumanji', release_date: '30/10/2019

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'},
  ]
}

The Dart Knight, The groupBy function returns a map object. In order to further group the elements by originCountry and space, we will loop the keys in the  groupBy<S, T>function. Map<T, List<S>>groupBy<S, T>(. Iterable<S>values, Tkey(. Selement. Groups the elements in valuesby the value returned by key. Returns a map from keys computed by keyto a list of all values for whichkeyreturns that key. The values appear in the list in the same relativeorder as in values.

This is a method naively implemented (in case you don't want to use the groupBy function from the collections package):

List<Map<String, List<Map<String, String>>>> MapByKey(String keyName, String newKeyName, String keyForNewName, List<Map<String,String>> input) {
  Map<String, Map<String, List<Map<String, String>>>> returnValue = Map<String, Map<String, List<Map<String, String>>>>();
  for (var currMap in input) {
    if (currMap.containsKey(keyName)) {
      var currKeyValue = currMap[keyName];
      var currKeyValueForNewName = currMap[keyForNewName];
      if (!returnValue.containsKey(currKeyValue)){
        returnValue[currKeyValue] = {currKeyValue : List<Map<String, String>>()};  
      }
      returnValue[currKeyValue][currKeyValue].add({newKeyName : currKeyValueForNewName});
    }
  }
  return returnValue.values.toList();
}

void main() {
    var test = [
    {"title": 'Avengers', "release_date": '10/01/2019'},
    {"title": 'Creed', "release_date": '10/01/2019'},
    {"title": 'Jumanji', "release_date": '30/10/2019'},
  ];

  var testMapped = MapByKey("release_date", "name", "title", test);

  print("$testMapped");
}

The output is:

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

Add Iterable.groupBy · Issue #30376 · dart-lang/sdk · GitHub, I'm opening this issue in the context of Dart 2.0. I'd type it as Map<K,List<E>> groupBy<K>(K key(E element)) (that is, a map to lists, not  A list of the data you want to display in the list: required-groupBy: Function which maps an element to its grouped value: required-floatingHeader: When set to true the sticky header will float over the list: no: false: itemBuilder / indexedItemBuilder: Function which returns an Widget which defines the item. indexedItemBuilder provides the

It may not be the best solution. But it can give you an idea

List arrayData = [
  {"name": 'John', "gender": 'male'},
  {"name": 'James', "gender": 'male'},
  {"name": 'Mary', "gender": 'female'}
];

Retrieve list ​​by gender:

List males = arrayData.where((o) => o['gender'] == "male").toList();
List females = arrayData.where((o) => o['gender'] == "female").toList();

Make new map with desired format:

List result = [
  {
    "male": males.map((f) => {"name": f['name']}).toList()
  },
  {
    "female": females.map((f) => {"name": f['name']}).toList()
  }
];

print:

debugPrint('${result}');

result:

[{male: [{name: John}, {name: James}]}, {female: [{name: Mary}]}]

Grouped list package for Flutter., A Flutter ListView where the list items can be grouped into sections. groupBy, Function which maps an element to its grouped value, required, -. itemBuilder /  elements: A list of the data you want to display in the list. groupBy: Function which maps an element to its grouped value. itemBuilder: Function which returns an Widget which defines the item. groupSeparator: Function which returns an Widget which defines the section separator.

Using the supercharged package, you'd write it like this:

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

final map = list.groupBy<String, Map>((item) => 
  item['release_date'],
  valueTransform: (item) => item..remove('release_date'),
);

Grouped list package for Flutter, A Flutter ListView in which list items can be grouped to sections. groupBy : Function which maps an element to its grouped value. itemBuilder  Sorting a List in Dart/Flutter. Map.map() method to transform a Map in Dart/Flutter. We can use map() method to get a new Map with all entries are transformed. For example, the code below change keys and uppercase values of all entries.

collection, Published Jun 19, 2020 • dart.dev. 37 likes. Dart native js. Flutter Android iOS web Equalities are provided for Iterable s, List s, Set s, and Map s, as well as  We can also convert a Dart Map to List using Iterable forEach () method instead. map.entries.forEach ( (e) => list.add (Customer (e.key, e.value))); print (list); We apply forEach () to entries property of the map. Every entry has a key-value field, we use them to create a new Customer object and add to the list.

Dart/Flutter - Convert Map to List & List to Map, Dart/Flutter convert Map to List example, convert List to Map example using many ways: Map.fromIterable(), Map.forEach(), Iterable forEach() or  The map literal you wrote will iterate the entries, and their keys and values, in the order they occur in the source, but not all maps guarantee that. If you actually need a list of pairs of strings, I'd recommend making your data that from the beginning, instead of using a map.

A Flutter ListView in which items can be grouped into sections, A Flutter ListView in which list items can be grouped to sections. screenshot-for- import 'package:grouped_list/grouped_list.dart';. Dart. Instead of in the list. groupBy : Function which maps an element to its grouped value. elements: A list of the data you want to display in the list (required). groupBy : Function which maps an element to its grouped value (required). itemBuilder or indexedItemBuilder : Function which returns an Widget which defines the item.

Comments
  • Can you please let me know how did you get data like 'var data' as mentioned above, when fetching data from API, because when I tried to get data from API it gives me data in (key,value) pair.
  • Note that this groupBy is not part of the dart:collection -- this references a third-party collection package.
  • How do I groupby on year in the same above example? release_date is still in Date format
  • I don't know why I wrote name instead of title in the result but you solved my problem thanks!
  • Group is a subset of Fold. I think that an implementation based on Fold would perform better and be more readable.
  • @Oswin Noetzelmann Can you please let me know how did you get data like 'var test' as mentioned above, when fetching data from API, because when I tried to get data from API it gives me data in (key,value) pair.
  • @Darshana the var test example is the exact structure that the OP had asked for in his question above.
  • Scan the list extracting the group-by value into a HashSet then, for each member of that set, use @EdHuamani's where syntax.
  • I just edited my problem. As you see, the key I need to groupBy is dynamic so I can't use this method.