Home > front end >  Dart: Sum of comman elements as an separate list?
Dart: Sum of comman elements as an separate list?

Time:02-01

In dart . I am having a list of payments per month with Repeating months :

class Pay {
String month;
int amount;
}

final payments = [Pay("Jan",150),Pay("Jan",100),Pay("Mar",120),Pay("Mar",150)];

Now my need is , I need to build a new list by adding common months payments , like this

[
Pay("Jan",250),
Pay ("Mar",270),
]

I had done this in nested for loops , but the code is rejected in Merge review

I need to try them using Map Reduce methods such as reduce,fold,expand etc with sorter amount of code

Please help me

CodePudding user response:

Try this:

main() {
  final payments = [
    Pay("Jan", 150),
    Pay("Jan", 100),
    Pay("Mar", 120),
    Pay("Mar", 150)
  ];
  Map<String, int> map = {};
  for (var pay in payments) {
    map[pay.month] =
        map[pay.month] == null ? pay.amount : map[pay.month]!   pay.amount;
  }
  List<Pay> newPays = [];
  map.forEach((key, value) => newPays.add(Pay(key, value)));
  print(newPays); //[Pay(Jan, 250), Pay(Mar, 270)]
}

CodePudding user response:

You can do something like the following where you are using fold together with a Map<String, Pay> to sum up the elements as you come across them. We are then taking the values of this map as the result.

class Pay {
  String month;
  int amount;

  Pay(this.month, this.amount);

  @override
  String toString() => 'Pay($month, $amount)';
}

void main() {
  final payments = [
    Pay("Jan", 150),
    Pay("Jan", 100),
    Pay("Mar", 120),
    Pay("Mar", 150)
  ];

  final paymentsSumList = payments
      .fold<Map<String, Pay>>(
        {},
        (map, pay) => map
          ..update(pay.month, (sumPay) => sumPay..amount  = pay.amount,
              ifAbsent: () => Pay(pay.month, pay.amount)),
      )
      .values
      .toList();

  print(paymentsSumList); // [Pay(Jan, 250), Pay(Mar, 270)]
}
  •  Tags:  
  • Related