Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dart - How to count items' occurence in a List

I am new to Dart. Currently I have a List of duplicate items, and I would like to count the occurence of them and store it in a Map.

var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];

I want to have a result like:

{
  "a": 3,
  "b": 2,
  "c": 2,
  "d": 2,
  "e": 2,
  "f": 1,
  "g": 1,
  "h": 3
}

I did some research and found a JavaScript solution, but I don't know how to translate it to Dart.

var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Play around with this:

  var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
  var map = Map();

  elements.forEach((element) {
    if(!map.containsKey(element)) {
      map[element] = 1;
    } else {
      map[element] +=1;
    }
  });

  print(map);

What this does is:

  • loops through list elements
  • if your map does not have list element set as a key, then creates that element with a value of 1
  • else, if element already exists, then adds 1 to the existing key value

Or if you like syntactic sugar and one liners try this one:

  var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
  var map = Map();

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

  print(map);

There are many ways to achieve this in all programming languages!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...