Looking for some help how to select oldest age from users in flutter object list...
users = [
{ id: 123, name: 'Bob', age: 25},
{ id: 345, name: 'Joe', age: 44},
...
];
I'd use the list reduce
function, docs here.
var oldestUser = users.reduce((currentUser, nextUser) => currentUser['age'] > nextUser['age'] ? currentUser : nextUser)
First make sure your list has the correct type and format:
List<Map<String, dynamic>> users = [
{"id": 123, "name": "Bob", "age": 25},
{"id": 345, "name": "Joe", "age": 44},
{"id": 35, "name": "Joxe", "age": 40},
];
Then you can do this:
if (users != null && users.isNotEmpty) {
users.sort((a, b) => a['age'].compareTo(b['age']));
print(users.last['age']);
}
Another way would be:
if (users != null && users.isNotEmpty) {
dynamic max = users.first;
users.forEach((e) {
if (e['age'] > max['age']) max = e;
});
print(max['age']);
}
Another one:
if (users != null && users.isNotEmpty) {
print(users.fold<int>(0, (max, e) => e['age'] > max ? e['age'] : max));
}
And this one requires import 'dart:math'
:
if (users != null && users.isNotEmpty) {
print(users.map<int>((e) => e['age']).reduce(max));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With