user15037387
user15037387

Reputation:

How to check if specific character exist in array and create two different arrays in Dart?

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

Upvotes: 0

Views: 861

Answers (3)

Kishan Dhankecha
Kishan Dhankecha

Reputation: 1015

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);
    }
  });
}

Upvotes: 1

Nagual
Nagual

Reputation: 2088

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);

Upvotes: 1

Prashant Vaddoriya
Prashant Vaddoriya

Reputation: 615

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.

Upvotes: 0

Related Questions