skip to Main Content

i would like to sort Uint8list or List lists in flutter

Example in js:

[ Uint8Array.from([1, 2, 3]), Uint8Array.from([0, 1, 2]) ].sort() -> [[0, 1, 2], [1, 2, 3]]

Thx

2

Answers


  1. you can use this mehode:

    List<List<int>> sortedList(List<List<int>> listOfList) {
    int maxLength = 0;
    for (var list in listOfList) {
      list.sort((a, b) => a.compareTo(b));
      if (list.length > maxLength) maxLength = list.length;
    }
    for (int i = 0; i < maxLength; i++) {
      listOfList.sort((a, b) {
        if(a.length-1<i || b.length-1<i) return 0;
        return (a[i].compareTo(b[i]));
      });
    }
    return listOfList;
    }
    

    input:

    [[3, 5, 8, 9], [3, 4, 8],[5, 9, 8],[5, 3, 8]]

    output:

    [[3, 4, 8], [3, 5, 8, 9], [3, 5, 8], [5, 8, 9]]

    Login or Signup to reply.
  2. I’m presuming you want to sort the List<int>s in a similar way to lexicographical sorting of Strings. That is, list1 should precede list2 if list1[n] < list2[n] for some n and if list1[i] == list2[i] for all i < n. If so, basically write a string comparison function but for ints:

    1. Compare each corresponding element.
    2. If they’re not equal, return that comparison result, otherwise keep iterating.
    3. If you run out of elements, return a comparison result that puts the shorter List first.
    import 'dart:typed_data';
    
    int compareListInts(List<int> list1, List<int> list2) {
      for (var i = 0; i < list1.length && i < list2.length; i += 1) {
        if (list1[i] < list2[i]) {
          return -1;
        } else if (list1[i] > list2[i]) {
          return 1;
        }
      }
    
      if (list1.length < list2.length) {
        return -1;
      } else if (list1.length > list2.length) {
        return 1;
      }
    
      return 0;
    }
    
    void main() {
      var listOfLists = [
        Uint8List.fromList([1, 2, 3]),
        Uint8List.fromList([0, 1, 2]),
        Uint8List.fromList([2, 3]),
        Uint8List.fromList([0, 1]),
      ];
    
      listOfLists
        ..sort(compareListInts)
        ..forEach(print);
    }
    

    which prints:

    [0, 1]
    [0, 1, 2]
    [1, 2, 3]
    [2, 3]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search