Lymp
Lymp

Reputation: 973

How to sort a list of strings by using the order of the items in another list?

I want to sort a list of strings (with possibly duplicate entries) by using as ordering reference the order of the entries in another list. So, the following list is the list I want to sort

List<String> list =  ['apple','pear','apple','x','x','orange','x','pear'];

And the list that specifies the order is

List<String> order = ['orange','apple','x','pear'];

And the output should be

List<String> result = ['orange','apple','apple','x','x','x','pear','pear'];

Is there a clean way of doing this?

I don't understand if I can use list's sort and compare with the following problem. I tried using map, iterable, intersection, etc.

Upvotes: 5

Views: 1806

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657536

There might be a more efficient way but at least you get the desired result:

main() {
  List<String> list =  ['apple','pear','apple','x','x','orange','x','pear'];
  List<String> order = ['orange','apple','x','pear'];
  list.sort((a, b) => order.indexOf(a).compareTo(order.indexOf(b)));
  print(list);
}

Try it on DartPad

The closure passed to list.sort(...) is a custom comparer which instead of comparing the passed item, compares their position in order and returns the result.

Using a map for better lookup performance:

main() {
  List<String> list =  ['apple','pear','apple','x','x','orange','x','pear'];
  List<String> orderList = ['orange','apple','x','pear'];
  Map<String,int> order = new Map.fromIterable(
      orderList, key: (key) => key, value: (key) => orderList.indexOf(key));
  list.sort((a, b) => order[a].compareTo(order[b]));
  print(list);
}

Try it on DartPad

Upvotes: 7

Related Questions