Home > Enterprise >  Dart: Sum values in list based on condition: Calculate List value based on ID?
Dart: Sum values in list based on condition: Calculate List value based on ID?

Time:03-03

I have list, I want to get total number of quantities available

var itemlist=[{"item_name":"32inch Tv","barnd":"samsung","qty":12},
              {"item_name":"32inch Tv","barnd":"realme","qty":10},
              {"item_name":"55inch Tv","barnd":"samsung","qty":10},
              {"item_name":"55inch Tv","barnd":"mi","qty":36},
              {"item_name":"40inch Tv","barnd":"sony","qty":20},
              {"item_name":"40inch Tv","barnd":"vu","qty":12}];

in dart how to get sum of "qty" based on "item_name"?

like

32inch Tv =22
55inch Tv =46
40inch Tv =32

how to get this result???

as

 List<int> qty=[22,46,32];

CodePudding user response:

What you need to do is, collect all in a map as a key value pair and get the quantities at the end by adding one by one.

void main() {
  final itemlist = [{"item_name":"32inch Tv","barnd":"samsung","qty":12},
              {"item_name":"32inch Tv","barnd":"realme","qty":10},
              {"item_name":"55inch Tv","barnd":"samsung","qty":10},
              {"item_name":"55inch Tv","barnd":"mi","qty":36},
              {"item_name":"40inch Tv","barnd":"sony","qty":20},
              {"item_name":"40inch Tv","barnd":"vu","qty":12}];
  
  final values = <String, int>{};
  
  for (int i = 0; i < itemlist.length; i  ) {
    final item = itemlist[i];
    final itemName = item['item_name'] as String;
    final qty = item['qty'] as int;
    int previousValue = 0;
    if (values.containsKey(itemName)) {
      previousValue = values[itemName]!;
    }
    previousValue = previousValue   qty;
    values[itemName] = previousValue;
  }
  
  final result = values.values;
  print('result: $result');
}

CodePudding user response:

void main() {
  var itemlist=[{"item_name":"32inch Tv","barnd":"samsung","qty":12},
              {"item_name":"32inch Tv","barnd":"realme","qty":10},
              {"item_name":"55inch Tv","barnd":"samsung","qty":10},
              {"item_name":"55inch Tv","barnd":"mi","qty":36},
              {"item_name":"40inch Tv","barnd":"sony","qty":20},
              {"item_name":"40inch Tv","barnd":"vu","qty":12}];
  var result = itemlist
     .where((e) => e['item_name'] == '55inch Tv')
     .map((e) => e['qty'] as int)
    .reduce((x,y) => x y);
  print(result);
}

Output:

46
  • Related