Home > other >  how to intersect multiple Maps (dictionary) in Dart
how to intersect multiple Maps (dictionary) in Dart

Time:08-28

I have a List consisting of multiple Maps (Dictionaries) regardless of the value of each element in the map

var list = [{'a':1, 'b':1, 'c':7},
            {'J':8, 'b':2, 'e':2},
            {'l':1, 'b':3, 'r':4},
            {'u':9, 'k':7} ];

Note that I don't know how many maps the list will have. It could be 0 and could be 1000 (I read from a JSON file).

I want to intersect them so the output would be like this:

var res = 'b';

I've done it in python by using this method:

res = set.intersection(*map(set, list))

CodePudding user response:

The following would do the trick. It folds the list by intersecting the map keys one by one.

final list = [
  {'a': 1, 'b': 1, 'c': 7},
  {'J': 8, 'b': 2, 'e': 2},
  {'l': 1, 'b': 3, 'r': 4},
  {'u': 9, 'b': 7}
];

final res = list.fold<Set<String>>(
  list.first.keys.toSet(),
  (result, map) => result.intersection(map.keys.toSet()),
);

print(res); // Prints: {b}
  • Related