0

I have the array of Strings, but I need to filter and create two arryas from one array, where can be all Items with character "A" and all Item with character "B".

List<String> coffeeMenu = ['Item A' , 'Item B', 'Item A', 'Item B', 'Item  A', 'Item B'];

The suppoused output is:

['Item A','Item A','Item  A']
['Item B', 'Item B', 'Item B'];

I have read that my tasks can be solved by using contains method, and i tried to do something like this:

if(coffeeMenu.contains('A')){
  print(coffeeMenu);
}else{
  coffeeMenu.contains('B');
  print(coffeeMenu);
}

But as I said I need not only to ckeck if A nad B character are existed but also fall it apart in two arrays. How can I do that?

I will be glade if you help me

1
  • use groupListsBy Commented Jun 30, 2021 at 6:50

3 Answers 3

1

You can possibly do something like this.

Try this on Dartpad.

void main() {
  sortArray();
  print(listWithA);
  print(listWithB);
}

List<String> coffeeMenu = [
  'Item A',
  'Item B',
  'Item A',
  'Item B',
  'Item A',
  'Item B'
];

List<String> listWithA = [];
List<String> listWithB = [];


void sortArray() {
  coffeeMenu.forEach((element) {
    if (element.toLowerCase().contains('a')) {
      listWithA.add(element);
    } else if (element.toLowerCase().contains('b')) {
      listWithB.add(element);
    }
  });
}
Sign up to request clarification or add additional context in comments.

Comments

1
final coffeeMenu = <String>['Item A' , 'Item B', 'Item A', 'Item B', 'Item  A', 'Item B'];
final itemsA = coffeeMenu.where((m) => m.contains('A')).toList();
final itemsB = coffeeMenu.where((m) => m.contains('B')).toList();
print(itemsA);
print(itemsB);

Comments

0

try this:-

 List<String> list = ['A', 'A', 'A', 'B', 'B', 'B'];
                          List<String> itemA = [];
                          List<String> itemB = [];
                          itemA.clear();
                          itemB.clear();
                          list.forEach((element) {
                            if (element
                                .toLowerCase()
                                .contains('A'.toLowerCase())) {
                              itemA.add(element);
                            }
                            if (element
                                .toLowerCase()
                                .contains('B'.toLowerCase())) {
                              itemB.add(element);
                            }
                          });

its worked for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.