sortRecursive static method

List sortRecursive(
  1. List list, {
  2. int compare(
    1. dynamic,
    2. dynamic
    )?,
})

Recursively sorts list. Nested lists are sorted at every depth; values of mixed types fall back to string comparison.

Arr.sortRecursive([[3, 1, 2], [9, 7, 8]]); // [[1, 2, 3], [7, 8, 9]]

Implementation

static List sortRecursive(
  List list, {
  int Function(dynamic, dynamic)? compare,
}) {
  final c =
      compare ??
      (a, b) {
        if (a == null) return b == null ? 0 : -1;
        if (b == null) return 1;
        if (a is Comparable &&
            b is Comparable &&
            a.runtimeType == b.runtimeType) {
          return a.compareTo(b);
        }
        return a.toString().compareTo(b.toString());
      };
  return list.map((v) {
    if (v is List) return sortRecursive(v, compare: compare);
    return v;
  }).toList()..sort(c);
}