How do you get the min and max values of a List in Dart.
[1, 2, 3, 4, 5].min //returns 1 [1, 2, 3, 4, 5].max //returns 5
I'm sure I could a) write a short function or b) copy then sort the list and select the last value,
but I'm looking to see if there is a more native solution if there is any.
Check if Dart List contains Element using List.contains(element) returns true if the element is present in this list. Else, it returns false.
If you don't want to import dart: math
and still wants to use reduce
:
main() { List list = [2,8,1,6]; // List should not be empty. print(list.reduce((curr, next) => curr > next? curr: next)); // 8 --> Max print(list.reduce((curr, next) => curr < next? curr: next)); // 1 --> Min }
Assuming the list is not empty you can use Iterable.reduce :
import 'dart:math'; main(){ print([1,2,8,6].reduce(max)); // 8 print([1,2,8,6].reduce(min)); // 1 }
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