0
void main (){
  print(occurence("hello hi hello one two two three"));
}

occurence(text){
  var words = text.split(" ");
  print(words);
  var count = {};
  words.map((element) => {
    if (count[element]){
      count[element]+=1
    }else{
     count[element] =1
      }
  });
  return count;
}

I want to get this output: {hello:2, hi:1, one:1, two:2, three:1}

Where's the problem in my code, I just get {} when I run the program.

Ayz
  • 181
  • 1
  • 9

1 Answers1

3

You should use the update function like this:

void main() {
  print(occurence("hello hi hello one two two three"));
  // {hello: 2, hi: 1, one: 1, two: 2, three: 1}
}

Map<String, int> occurence(String text) {
  List<String> words = text.split(" ");
  print(words); // [hello, hi, hello, one, two, two, three]

  Map<String, int> count = {};
  for (var word in words) {
    count.update(word, (value) => value + 1, ifAbsent: () => 1);
  }

  return count;
}
julemand101
  • 28,470
  • 5
  • 52
  • 48
VincentDR
  • 696
  • 3
  • 15
  • If you try it on DartPad, still has the same problem, Maybe you are right about update function but there is something missing in the syntax. I don't know – Ayz Oct 28 '22 at 08:45
  • Yes, little mistake using map, better to do it with the for loop – VincentDR Oct 28 '22 at 08:49