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?
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']]