I'm new to Dart/Flutter. I don't know how to count items from a 2d list.

List<List<bool>> a = [
    [true, true, false, false],
    [true, false, false, true]
];

I want to count true in this list, but in vertically.

So I want a result like this:

result = [2, 1, 0, 1]

Thank you!


Solution 1: Vijay

you can use the spread operator to assign length of inner list to a resultant array like this

 void main() {
   const a = [
    [true, true, false],
    [true, false, false, true, true]
];

  var result = [];
  for(var element in a) {
    var count = 0;
    for (var el in element) {
      if (el) {
        count += 1;
      }
    }
    result = [...?result,count];
  }
  print(result);
}

try this code in Dartpad


Solution 2: Ουιλιαμ Αρκευα

extension on List<bool> {
List<int> addIfTrue(List<int> counter) {
if (counter.length == length && counter.isNotEmpty) {
var i = 0;
forEach((e) => e ? counter[i++]++ : i++);
return counter;
}
return [];
}
}

void main() { var a = [ [true, true, false, false], [true, false, false, true] ]; var n = a[0].length; var z = a.fold<List<int>>(List.filled(n, 0), (prev, e) => e.addIfTrue(prev)); print(z); }

Result:

[2, 1, 0, 1]