Mason Horder
Mason Horder

Reputation: 108

Flutter sort List with value of a list by value of List Within List

Basically, I have a list of scores and their corresponding index. I want to sort "scores" by a value within that list.

scores = [[0, 340], [1, 69], [2, 485], [3, 194], [4, 91], [5, 130], [6, 110], [7, 655], [8, 45], [9, 445], [10, 34], [11, 385]]

I want to sort the list by the second value within that list. The end result should be something like: scores = [[10,34], [8,45], [1,69].....]

scores.sort(); gives an error saying List is non-comparable

Thanks, Mason

Upvotes: 0

Views: 56

Answers (1)

void main() {
  var scores = [[0, 340], [1, 69], [2, 485], [3, 194], [4, 91], [5, 130], [6, 110], [7, 655], [8, 45], [9, 445], [10, 34], [11, 385]];
  
  print(scores);
  
  scores.sort((a,b) => a[1].compareTo(b[1]));
  print(scores);  
}

Result:

[[10, 34], [8, 45], [1, 69], [4, 91], [6, 110], [5, 130], [3, 194], [0, 340], [11, 385], [9, 445], [2, 485], [7, 655]]

Upvotes: 2

Related Questions