1

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.

TheCrzyMan
  • 1,010
  • 1
  • 11
  • 25
rengineer
  • 349
  • 3
  • 19
  • [This might help](https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – TheCrzyMan Jun 21 '18 at 12:33
  • Possible duplicate of [Swift how to sort array of custom objects by property value](https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – TheCrzyMan Jun 21 '18 at 12:34

1 Answers1

1

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 }
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160