Home > Blockchain >  Flutter/Dart: How to count tags of array of list
Flutter/Dart: How to count tags of array of list

Time:07-06

How can I count tags of an array? I have this code:

class Product{
  Product({required this.name, required this.tags});
  final String name;
  final List<String> tags;

}

void TagList(){

  final product =[
    Product(name: 'bmw', tags: ['car', 'm3']),
    Product(name: 'kia', tags: ['car', 'morning', 'suv']),
    Product(name: 'hyundai', tags: ['car', 'ev6', 'suv']),
  ];
}

How can I get how many times each tag was used?

Expected output:

car(3) m3(1) ev6(1) suv(2) morning(1)

CodePudding user response:

You can use this function to loop over the products list and get how many times each tag is used:

void printTags(List<Product> products) {
  final tagCount = <String, int>{};
  for (final product in products) {
    for (final tag in product.tags) {
      tagCount[tag] = tagCount.putIfAbsent(tag, () => 0)   1;
    }
  }
  print(tagCount);
}

Output:

{car: 3, m3: 1, morning: 1, suv: 2, ev6: 1}

Here's a complete runnable example:

void main() {
  final products = [
    Product(name: 'bmw', tags: ['car', 'm3']),
    Product(name: 'kia', tags: ['car', 'morning', 'suv']),
    Product(name: 'hyundai', tags: ['car', 'ev6', 'suv']),
  ];

  printTags(products);
}

class Product {
  Product({required this.name, required this.tags});
  final String name;
  final List<String> tags;
}

void printTags(List<Product> products) {
  final tagCount = <String, int>{};
  for (final product in products) {
    for (final tag in product.tags) {
      tagCount[tag] = tagCount.putIfAbsent(tag, () => 0)   1;
    }
  }
  print(tagCount);
}

CodePudding user response:

  final result = product.map((i) => i.tags)
    .expand((i) => i)
    .map((i) => {i: 1})
    .reduce((sum, i) => {
      ...sum, 
      ...{i.keys.first: (sum[i.keys.first] ?? 0)   1 }
    });
  • Related