user17336890
user17336890

Reputation:

Dart: transform a list into a number of occurrences list

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]

Upvotes: 1

Views: 158

Answers (2)

mohammad esmaili
mohammad esmaili

Reputation: 1737

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

Upvotes: 1

Temirlan Almassov
Temirlan Almassov

Reputation: 121

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

Upvotes: 1

Related Questions