How to use "reduce" to get the sum of values in a list of objects in Dart/Flutter

Viewed 2752

Let say i have a list of object like this:

provinces = [
{name:'cityA', population:1000, area:2000},
{name:'cityB', population:2500, area:1500},
{name:'cityC', population:5000, area:3000}
];

How can I use reduce in Dart to get an output with the sum of the population and area, like this:

{
population: 8500,
area: 6500
}
2 Answers

fold is equivalent to reduce, you could use It as below:

List provinces = [
  {"name":'cityA', "population":1000, "area":2000},
  {"name":'cityB', "population":2500, "area":1500},
  {"name":'cityC', "population":5000, "area":3000}
];

dynamic result = provinces.fold({"population": 0, "area": 0}, (preMap, map) {
  return {
    "population": preMap["population"] + map["population"],
    "area": preMap["area"] + map["area"],
  };
});
print(result);

Result:

{population: 8500, area: 6500}

For more about reduce vs fold, you might want to see the details that specified the topic.

You can achieve this using the reduce method in Dart. Check the code below: It works perfectly:

CODE

 // here is the initial list
  List provinces = [
    {"name":'cityA', "population":1000, "area":2000},
    {"name":'cityB', "population":2500, "area":1500},
    {"name":'cityC', "population":5000, "area":3000}
  ];

  // use the reduces method to sum the population and area
  Map<String, dynamic> sum = provinces.reduce((value, element){
    return {
      // sum the population here
      "population": value["population"] + element["population"],
      // sum the area here
      "area": value["area"] + element["area"],
    };
  });

  // print the sum here
  print(sum);

OUTPUT:

{
population: 8500,
area: 6500
}

To read more on the reduce method in dart, Check the link below:

Reuduce method in dart

I hope this helps.

Related