Flattening a list

A list can contain other lists as elements. This is effectively a two-dimensional list or array. Flattening means making a single list with all sublist items contained in it. Take a look at the different possibilities in flatten_list.dart.

How to do it...

We show three ways to flatten a list in the following code:

List lst = [[1.5, 3.14, 45.3], ['m', 'pi', '7'], [true, false, true]];
// flattening lst must give the following resulting List flat:
// [1.5, 3.14, 45.3, m, pi, 7, true, false, true]

void main() {
  // 1- using forEach and addAll:
  var flat = [];
  lst.forEach((e) => flat.addAll(e));
  print(flat);
  // 2- using Iterable.expand:
  flat = lst.expand((i) => i).toList();
  // 3- more nesting levels, work recursively:
  lst = [[1.5, 3.14, 45.3], ['m', 'pi', '7'], "Dart", [true, false, true]];
  print(flatten(lst));
}

How it works...

The simplest method uses a combination of forEach and addAll. The second method uses the fact that List implements Iterable, and so has the expand method. The expand method is used here with an identity function as its argument; every element is returned without applying a function.

Using expand does not work if the list contains ints (or Strings, doubles, and so on) as single list elements, or if there are multiple levels of nesting. In that case, we will have to work recursively, as implemented in the flatten method:

Iterable flatten(Iterable iterable)
  => iterable.expand((e) => e is List ? flatten(e) : [e]);

There's more...

Why would you want to flatten a list of lists? There may be application needs to do this, for example, when you use two-dimensional lists or matrices in the game logic, but an obvious reason is that working with a list of lists is much more expensive performance wise.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset