Home > Net >  Dart: Ordering a list by sequence in another list
Dart: Ordering a list by sequence in another list

Time:06-16

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:

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

CodePudding user response:

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.

  • Related