Sort a List in Dart based on how another List was sorted

1,663

You can achieve this by create a Map that holds the mappings for the letters to your numbers, i.e. 2 has a assigned to it, 3 has b etc.
Now you can sort your list normally and after that recreate your other list based on the mappings that you stored before sorting:

main() {
  List<String> letters = ["a", "b", "c"];
  final List<int> numbers = [2, 3, 1];

  final Map<int, String> mappings = {
    for (int i = 0; i < numbers.length; i++)
      numbers[i]: letters[i]
  };

  numbers.sort();

  letters = [
    for (int number in numbers) mappings[number]
  ];

  print(letters); // [c, a, b]
  print(numbers); // [1, 2, 3]
}

I used collection for for this example. This syntax for collection literals was introduced in Dart 2.3.
Learn more.

You can easily turn this about and map the numbers to your letters instead. That would look like this:

main() {
  final List<String> letters = ["a", "b", "c"];
  List<int> numbers = [2, 3, 1];

  final Map<String, int> mapping = {
    for (int i = 0; i < letters.length; i++)
      letters[i]: numbers[i]
  };

  letters.sort((a, b) => b.compareTo(a));

  numbers = [
    for (String letter in letters) mapping[letter]
  ];

  print(letters); // [c, b, a]
  print(numbers); // [1, 3, 2]
}

Note that I sorted the letters in a descending order here by turning about the compareTo as well (by default a.compareTo(b) is used by List.sort).

Share:
1,663
user9469335
Author by

user9469335

Updated on December 12, 2022

Comments

  • user9469335
    user9469335 over 1 year

    I am trying to sort a list with reference to another list. Consider this example,

    List<String> a = ["a", "b", "c"];
    List<int> b = [2, 3, 1];
    

    Now, I want the result to be like this,

    a = ["c", "a", "b"];
    b = [1, 2, 3];
    

    How can I achieve this result?