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.

2

1 Answer 1

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.