Reputation: 334
I'm struggling to understand how to sum multiple objects in a list together matching certain conditions
I have :
List<TruckFruit> = truckFruits;
class TruckFruit extends Equatable {
final String fruitType;
final int shape;
final int availableCount;
final int totalCount;
TruckFruit({
required this.fruitType,
required this.shape,
required this.availableCount,
required this.totalCount,
});
@override
List<Object?> get props => [
shape,
fruitType,
availableCount,
totalCount,
];
}
I'd like to sum multiple TruckFruit
inside this truckFruits
list which have equal fruitType
String &&
equal shape
int
such as from this list :
final List<TruckFruit> truckFruits = [
TruckFruit(fruitType: 'Apple', shape: 4, availableCount: 1, totalCount: 10),
TruckFruit(
fruitType: 'Strawberry', shape: 4, availableCount: 2, totalCount: 6),
TruckFruit(fruitType: 'Apple', shape: 4, availableCount: 8, totalCount: 30),
TruckFruit(
fruitType: 'Strawberry', shape: 2, availableCount: 5, totalCount: 8),
];
I'd like to get this list :
final List<TruckFruit> newTruckFruitsList = [
TruckFruit(fruitType: 'Apple', shape: 4, availableCount: 9, totalCount: 40), // the availableCount & totalCount were summed from the two Apples with same shape
TruckFruit(
fruitType: 'Strawberry', shape: 4, availableCount: 2, totalCount: 6),
TruckFruit(
fruitType: 'Strawberry', shape: 2, availableCount: 5, totalCount: 8),
];
Upvotes: 1
Views: 193
Reputation: 23134
This could do it:
final List<TruckFruit> newTruckFruitsList = truckFruits.fold(<TruckFruit>[], (previousValue, element) {
TruckFruit? match = previousValue.firstWhereOrNull(
(e) => e.shape == element.shape && e.fruitType == element.fruitType);
if (match != null) {
return previousValue
..remove(match)
..add(TruckFruit(
fruitType: element.fruitType,
shape: element.shape,
availableCount: element.availableCount + match.availableCount,
totalCount: element.totalCount + match.totalCount));
} else {
return previousValue..add(element);
}
});
You will need to
import 'package:collection/collection.dart';
to use firstWhereOrNull
Upvotes: 2
Reputation: 113
create newTruckFruitsList by looping through truckFruits and adding TruckFruit objects with unique fruitTypes.
and double loop through newTruckFruitsList-truckFruits and add availableCount, totalCount if fruitType and shape matches.
Upvotes: 0