How can I extract values from within a list

Viewed 27

Let us say that I have a Map in dart which holds value in this format : String, List<MyModel>. Now the Map would look something like this -

{
 'a' : [MyModel1, MyModel2],
 'b' : [MyModel3],
 'c' : [MyModel4, MyModel5]
}

I want to design a function that would return me this : [MyModel1, MyModel2,......,MyModel5] . I can easily do the same by iterating over values in the map and then use a nested loop to iterate over each value to finally extract each of the elements. However, what I want is a better way to do it (probably without using the two for loops as my Map can get pretty long at times.

Is there a better way to do it ?

1 Answers

You could use a Collection for and the ... spread operator, like this:

void main() {
  Map<String, List<int>> sampleData = {
    'a': [1, 2],
    'b': [3],
    'c': [4, 5, 6]
  };

  final output = mergeMapValues(sampleData);
  print(output); // [1, 2, 3, 4, 5, 6]
}

// Merge all Map values into a single list
List<int> mergeMapValues(Map<String, List<int>> sampleData) {
  final merged = <int>[for (var value in sampleData.values) ...value]; // Collection for
  return merged;
}

Here's the above sample in Dartpad: https://dartpad.dev/?id=5b4d258bdf3f9468abbb43f7929f4b73

Related