Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart List min/max value

Tags:

dart

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.

like image 790
basheps Avatar asked Dec 10 '13 09:12

basheps


People also ask

How do you check if a value is in a list Dart?

Check if Dart List contains Element using List.contains(element) returns true if the element is present in this list. Else, it returns false.


2 Answers

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 } 
like image 43
Murali Krishna Regandla Avatar answered Oct 13 '22 05:10

Murali Krishna Regandla


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 } 
like image 111
Alexandre Ardhuin Avatar answered Oct 13 '22 05:10

Alexandre Ardhuin