I'm having trouble sorting a list of objects by the highest value in a nested map in each. I've looked through many similar questions here on SO but am none the wiser. Any help would be greatly appreciated.
My list looks like this:
{
"stores": [
{
"id": 305,
"title": "Store 1",
"discounts": [
{
"id": 335,
"category": "Books",
"type": "percentage",
"minDiscount": 0,
"maxDiscount": 1.25
},
{
"id": 337,
"category": "Gift cards",
"type": "percentage",
"minDiscount": 0,
"maxDiscount": 8.5
},
{
"id": 338,
"category": "Merchandise",
"type": "percentage",
"minDiscount": 0,
"maxDiscount": 2.5
}
]
},
{
"id": 304,
"title": "Store 2",
"discounts": [
{
"id": 340,
"category": "New Customer",
"type": "percentage",
"minDiscount": 0,
"maxDiscount": 5
},
{
"id": 339,
"category": "Existing Customer",
"type": "percentage",
"minDiscount": 0,
"maxDiscount": 2.5
}
]
},
{
"id": 303,
"title": "Store 3",
"discounts": [
{
"id": 341,
"category": "General",
"type": "percentage",
"minDiscount": 0,
"maxDiscount": 7.3
}
]
},
{
"id": 302,
"title": "Store 4",
"discounts": [
{
"id": 333,
"category": "New customers",
"type": "percentage",
"minDiscount": 0,
"maxDiscount": 3
}
]
},
{
"id": 301,
"title": "Store 5",
"discounts": [
{
"id": 332,
"category": "General",
"type": "percentage",
"minDiscount": 0,
"maxDiscount": 9
}
]
}
]
}
My expected result is the stores listed based on highest discount available in each of their 'discounts' Map property. The output:
You can try this approach, if your desired output is:
stores.sort((a, b) {
List discountsInA = a["discounts"];
List discountsInB = b["discounts"];
dynamic maxDiscountInA = discountsInA.fold<dynamic>(
0, (max, e) => e['maxDiscount'] > max ? e['maxDiscount'] : max);
dynamic maxDiscountInB = discountsInB.fold<dynamic>(
0, (max, e) => e['maxDiscount'] > max ? e['maxDiscount'] : max);
return maxDiscountInA > maxDiscountInB
? -1
: maxDiscountInA < maxDiscountInB
? 1
: 0;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.