Home > Software engineering >  Expand list (array) in dart with separator
Expand list (array) in dart with separator

Time:07-23

I'm searching for a way to expand a list with a seperator between each list.

Example (add 0 between sublists):

what I have is this:

List<List<int>> list = [[1,2,3],[4,5,6],[7,8,9]];

what I want:

List<int> newList = [1,2,3,0,4,5,6,0,7,8,9] 

list.expand((element) => element) can combine the sublist to this: [1,2,3,4,5,6,7,8,9]

but the separator iss missing :-(

CodePudding user response:

You can expand like this with adding separator item.

list.expand((element)=>[...element,0])

UPDATE

 list.reduce((a,b)=>[...a,0,...b])

CodePudding user response:

One solution would be to make an extension to Iterable like expandWithSeparator with support for a separator value:

void main() {
  List<List<int>> list = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ];

  print(list.expandWithSeparator((element) => element, 0).toList());
  // [1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9]
}

extension<E> on Iterable<E> {
  Iterable<T> expandWithSeparator<T>(
    Iterable<T> Function(E element) toElements,
    T separator,
  ) sync* {
    bool first = true;

    for (final element in this) {
      if (first) {
        first = false;
      } else {
        yield separator;
      }
      yield* toElements(element);
    }
  }
}
  • Related