Saurabh Pandey
Saurabh Pandey

Reputation: 151

how to count number of occurrences of element in list of maps in dart?

I have a list of maps like this

data = [
{
  'id': 100,
  'quantity': 20
},
{
  'id': 101,
  'quantity': 25
},
{
  'id': 101,
  'quantity': 30
}
{
  'id': 105,
  'quantity': 50
}
]

I am able to count occurrences of element in a list like this


 data.forEach((x) => map[x] = !map.containsValue(x) ? (1) : (map[x] + 1));
 print(map);

Output : 
{{id: 100, quantity: 20}: 1, {id: 101, quantity: 25}: 1, {id: 101, quantity: 30}: 1, {id: 105, quantity: 50}: 1}

But I want to count how many times id = 101 comes in the list so How can I achieve that?

Upvotes: 3

Views: 7134

Answers (1)

Augustin R
Augustin R

Reputation: 7799

You can use where to filter your array of maps and then use the getter length :

var data = [
  {'id': 100, 'quantity': 20},
  {'id': 101, 'quantity': 25},
  {'id': 101, 'quantity': 30},
  {'id': 105, 'quantity': 50}
];
print(data.where((e) => e['id'] == 101).length); // 2

Upvotes: 13

Related Questions