Reputation: 359
I am trying to sort an array as shown:
var arrayTst = [
[12443, "Starbucks", "Coffee1", "Coffee11", "Tea1", "Drinks1"],
[12495, "Coffee Bean", "Coffee2", "Tea2", "Cookies2"],
[13000, "GroceryMarket", "Tea3", "Bubble Tea3", "Shaved Ice3", "Mangoes"],
[10000, "Costco", "Soda4", "Salads4", "Pizza4"]
]
How can I sort this list from least to greatest using the first index(which shows the distance)? For example, since I want this array to sort from least to greatest by distance, I would want it to sort to :
var arrayTst = [
[10000, "Costco", "Soda4","Salads4","Pizza4"],
[12443, "Starbucks", "Coffee1","Coffee11", "Tea1", "Drinks1"],
[12495, "Coffee Bean", "Coffee2", "Tea2","Cookies2"],
[13000, "GroceryMarket", "Tea3", "Bubble Tea3", "Shaved Ice3", "Mangoes"]
]
The distance was calculated using .distance(from: currentLocation) and placing into the array via for loop.
Upvotes: 1
Views: 204
Reputation: 53092
You need to re-consider your data structure. Rather than just an array of Any
, it looks like you have an array of…
struct Store {
let distance: Double
let name: String
let products: [String]
}
Then…
var arrayTst = [
Store(distance: 12443, name: "Starbucks", products: ["Coffee11", "Tea1", "Drinks1"]),
Store(distance: 12495, name: "Coffee Bean", products: ["Coffee2", "Tea2", "Cookies2"]),
etc…
]
let sortedArray = arrayTst.sorted { $0.distance < $1.distance }
Upvotes: 1