Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dart: Ordering a list by sequence in another list

I have the following list made up of CustomerName and SalesId example:

List1

  • StoreA – 001
  • StoreB – 002
  • StoreB – 003
  • StoreC – 004

In the next part im extracting the unique CustomerName from List1 and putting them in List2, this list will be reordered to the user’s liking and may end up looking something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List2

  • StoreB
  • StoreC
  • StoreA

Now I want to reorder List1 based on the sequence of list2 (SalesId sequence doesn’t matter)

  • StoreB – 002
  • StoreB – 003
  • StoreC – 004
  • StoreA – 001

>Solution :

You could create a map based on index2 which can be used to lookup the sorting order. So something like this:

void main() {
  final List<Store> list1 = [
    Store(customerName: 'StoreA', salesId: '001'),
    Store(customerName: 'StoreB', salesId: '002'),
    Store(customerName: 'StoreB', salesId: '003'),
    Store(customerName: 'StoreC', salesId: '004'),
  ];

  final List<String> list2 = [
    'StoreB',
    'StoreC',
    'StoreA',
  ];

  final Map<String, int> _sortingOrderMap = {
    for (var i = 0; i < list2.length; i++) list2[i]: i
  };

  print(_sortingOrderMap);
  // {StoreB: 0, StoreC: 1, StoreA: 2}

  list1.forEach(print);
  // StoreA - 001
  // StoreB - 002
  // StoreB - 003
  // StoreC - 004

  list1.sort((s1, s2) => _sortingOrderMap[s1.customerName]!
      .compareTo(_sortingOrderMap[s2.customerName]!));

  list1.forEach(print);
  // StoreB - 002
  // StoreB - 003
  // StoreC - 004
  // StoreA - 001
}

class Store {
  final String customerName;
  final String salesId;

  Store({required this.customerName, required this.salesId});

  @override
  String toString() => '$customerName - $salesId';
}

You might need to modify the solution if you need to handle cases of customerName not being in list2 if that is a possible scenario.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading