Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: Map class, reduce (or otherwise find certain information)

Tags:

flutter

dart

New to Dart (Flutter), and the docs don't seem to have a method for the Map class that will allow me to do this easily...

I want to have a Map with keys of Datetime and values of calories eaten.

{'2019-07xxx': 350, '2019-07xxx': 500, ...}

Now, what's the best way to filter this so that I only get values from today? (i.e. when starting the app and pulling the data from storage)

Ideally once I do that, I can get the cumulative value of today's calories so far with:

var sum = todaysCaloriesArray.reduce((a, b) => a + b);

Unless there is some Dart-fu that would allow this in a better way?

like image 752
Matt Takao Avatar asked Jul 23 '19 01:07

Matt Takao


2 Answers

You could use .where on the map's entries. For example:

  var map = Map<String, int>();
  var sum = map.entries
      .where((e) => e.key.startsWith('2019-07-22'))
      .map<int>((e) => e.value)
      .reduce((a, b) => a + b);
like image 178
Richard Heap Avatar answered Sep 21 '22 17:09

Richard Heap


The first answer was great! But you can use the fold method so you can use in empty collections.

var map = Map<String, int>();
var sum = map.entries
  .where((e) => e.key.startsWith('2019-07-22'))
  .fold(0,(int a, b) => a + b.value);
like image 31
Alvaro Camillo Neto Avatar answered Sep 23 '22 17:09

Alvaro Camillo Neto