Md Golam Rahman Tushar
Md Golam Rahman Tushar

Reputation: 2375

Dart: split a list to two sublists based on condition

Have there any way to split a list in dart based on a condition like following:

[1, 2, 3, 4, 5, 6, 7, 8] (A sample list)

After splitting it based on i % 2 == 0 condition, 
it would generate the following two lists:
1) [1, 3, 5, 7]
2) [2, 4, 6, 8]

I know I can simply write a loop to go through all the elements and check the condition to create the two sublists. But have there any shorter functional way in dart? Thanks in advance!

Upvotes: 7

Views: 5255

Answers (2)

julemand101
julemand101

Reputation: 31219

If you want to do this a lot it could be a good idea to create an extension method in your project which does what you want. I have come up with the following design which should work in a generic and efficient way:

void main() {
  final s_list = [1, 2, 3, 4, 5, 6, 7, 8];
  final match = s_list.splitMatch((element) => element % 2 == 0);

  print(match.matched);   // [2, 4, 6, 8]
  print(match.unmatched); // [1, 3, 5, 7]
}

extension SplitMatch<T> on List<T> {
  ListMatch<T> splitMatch(bool Function(T element) matchFunction) {
    final listMatch = ListMatch<T>();

    for (final element in this) {
      if (matchFunction(element)) {
        listMatch.matched.add(element);
      } else {
        listMatch.unmatched.add(element);
      }
    }

    return listMatch;
  }
}

class ListMatch<T> {
  List<T> matched = <T>[];
  List<T> unmatched = <T>[];
}

Upvotes: 7

Marios
Marios

Reputation: 27350

A quick solution:

var s_list = [1, 2, 3, 4, 5, 6, 7, 8];

s_list.where( (el) => el % 2 == 0 ).toList();
s_list.where( (el) => el % 2 != 0 ).toList();

Upvotes: 3

Related Questions