'Dart - get the nearest(larger) value from List?

How can I find the closest value in a list, which will return me the higher value? Example: List of [3,7,12,19] if my value is 8 how can I get the nearest(larger) value 12? i want this logic in dart.



Solution 1:[1]

Just filter the List only for the values higher or equal to your number and get the lowest value:

var n = 8; // Number to match
var l = [3, 7, 12, 19]; // List of values

var greater = l.where((e) => e >= n).toList()..sort(); //List of the greater values

print(greater.first); // Print the first value. -> 12

Solution 2:[2]

Mattia's answer is already good enough. (although the list cant have the length 0 and it might be not as efficient, as you have a where() as well as sort() in there). Here is a different approach, that solves those concerns:

Nearest-Larger value

final nearestLarger = list.isEmpty ? null : list.reduce(
      (a, b) => (a-target).abs() < (b -target).abs() ? a : b);

Nearest-Smaller value

final nearestSmaller = list.isEmpty ? null : list.reduce(
      (a, b) => (a-target).abs() <= (b -target).abs() ? a : b);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Paul