Home > database >  Dart: transform a list into a number of occurrences list
Dart: transform a list into a number of occurrences list

Time:04-01

I saw examples on how to do kind of similar stuff but never exactly what I want, I'm wondering how to do it properly so if you can give me an hint I would be really happy ! :)

["a","a","b","a","c","c"] =====> [3,1,2]

CodePudding user response:

final list = ["a","a","b","a","c","c"];
Map<String, int> map = {};
for(var i in list){
  if(!map.containsKey(i)){
    map[i] = 1;
 }
  else{
    map[i]=map[i]! 1;
  }
}
print(map.values.toList());

CodePudding user response:

According to this question you can do like this:

var allStrings = ["a", "a", "b", "a", "c", "c"];
var map = Map();

allStrings.forEach((x) => map[x] = !map.containsKey(x) ? (1) : (map[x]   1));

print((map.values).toList());
  • Related