How do I split or chunk a list into equal parts, with Dart?

Seth Ladd picture Seth Ladd · Mar 8, 2014 · Viewed 11.6k times · Source

Assume I have a list like:

var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

I would like a list of lists of 2 elements each:

var chunks = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']];

What's a good way to do this with Dart?

Answer

cbracken picture cbracken · Mar 9, 2014

Quiver (version >= 0.18) supplies partition() as part of its iterables library (import 'package:quiver/iterables.dart'). The implementation returns lazily-computed Iterable, making it pretty efficient. Use as:

var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
var pairs = partition(letters, 2);

The returned pairs will be an Iterable<List> that looks like:

[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]