I need to sort unsortedList
based on the sorting of sortedList
.
Example:
List<String> sortedList = ["x", "a", "c", "d", "w"];
// [unsortedList] items need to be also in [sortedList] and in the
// same range (eg. between 0 and 2 position)
List<String> unsortedList = ["a", "x", "c"];
CodePudding user response:
You want the elements of sortedList
which also appear in unsortedList
, in their original order.
That's not about sorting.
No sorting is needed:
var result = sortedList.where({...unsortedList}.contains).toList();
(You can use unsortedList.contains
directly, instead of creating a set, and it's probably even faster for small unsortedList
s.)
Or, if your requirement is correct, and the n elements of unsortedList
are the first n elements of sortedList
in a different order, then maybe just var result = sortedList.sublist(0, unsortedList.length);
.
If you actually care about getting the element from unsortedList
, not the equal element from sortedList
(which may matter if the elements are equal, but not identical), you can do:
var result = sortedList.map({...unsortedList}.lookup).whereNotNull().toList();
where whereNotNull
is from package:collection
.
CodePudding user response: