JakesMD
JakesMD

Reputation: 2166

How to sort a list by another list

How can I sort a list with objects so that the properties of the objects match a different list in dart?

class Example {
  String _id;
  String get id => _id;
}

List examples = [Example(id: 'hey'), Example(id: 'foo'), Example(id: 'baa')]
List ids = ['foo', 'baa', 'hey']

print(examples.sortBy(ids)) ???????


OUTPUT:

  [Example(id: 'foo'), Example(id: 'baa'), Example(id: 'hey')]

Upvotes: 1

Views: 1182

Answers (1)

Abion47
Abion47

Reputation: 24616

This isn't the most performant way, but it's probably one of the simplest. Use a sorting method that sorts based on the object's field's location in the other array:

final sortedExamples = List.from(examples)
  ..sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));

This way is slightly more involved but more performant as you only need to iterate over each list once each. It involves making a map out of your list and then using that as the source of truth to rebuild a sorted list:

final ref = Map.fromIterable(examples, key: (e) => e.id, value: (e) => e);
final sortedExamples = List.from(ids.map((id) => ref[id]));

The first option is better if space is an issue, the second is better if speed is an issue.

Upvotes: 5

Related Questions