Reputation: 11
I currently have two lists, first list got ordered elements containing only lat/lon geocordinates, these are the waypoints on a delivery route and must be keep in this order. The second one got nested lists containing the String address of the location as the element [0], and the corresponding lat/lon of this address as element [1].
list1 = [[-22.7481495,-43.440236], [-22.7532378,-43.4541717], [-22.9976583,-43.3581268], [-22.8795337,-43.3373482]]
list2 = [[SAMPLE ADDRESS A, -22.9976583,-43.3581268], [SAMPLE ADDRESS B, -22.7481495,-43.440236], [SAMPLE ADDRESS C, -22.7532378,-43.4541717], [SAMPLE ADDRESS D, -22.8795337,-43.3373482]]
I need to order the second list based on the order I already have in the first one. Just for a quick example, list2[0] should be equal to [SAMPLE ADDRESS B, -22.7481495,-43.440236]
Upvotes: 1
Views: 447
Reputation: 1224
This should be what you're looking for:
void main() {
var list1 = [
[-22.7481495, -43.440236],
[-22.7532378, -43.4541717],
[-22.9976583, -43.3581268],
[-22.8795337, -43.3373482],
];
var list2 = [
["SAMPLE ADDRESS A", -22.9976583, -43.3581268],
["SAMPLE ADDRESS B", -22.7481495, -43.440236],
["SAMPLE ADDRESS C", -22.7532378, -43.4541717],
["SAMPLE ADDRESS D", -22.8795337, -43.3373482],
];
list2.sort((l1, l2) {
return list1.indexWhere((el) { return el[0] == l1[1] && el[1] == l1[2];}) -
list1.indexWhere((el) { return el[0] == l2[1] && el[1] == l2[2]; });
}
);
print(list2);
}
We are using the sort method (https://api.flutter.dev/flutter/dart-core/List/sort.html) to order the list, passing a Comparator
which compares the index where each element is located in list1
.
Upvotes: 1