0

I have an array for item names, and another for item prices. I want to sort the prices from least to greatest, but have the appropriate items and the prices be at the same index.

For example: [9, 4, 1] & ["item 1", "item 2", "item 3"] -> [1, 4, 9] & ["item 3", "item 2", "item 1"]

Any idea how i could do this efficiently for large arrays?

2

1 Answer 1

1

Given

let prices = [9, 4, 1]
let names = ["item 1", "item 2", "item 3"]

Solution #1

You can

let sorted = zip(prices, names).sorted { $0.0 < $1.0 }

let sortedPrices = sorted.map { $0.0 } // [1, 4, 9]
let sortedNames = sorted.map { $0.1 } // ["item 3", "item 2", "item 1"]

Solution #2

You should really use a model value.

let prices = [9, 4, 1]
let names = ["item 1", "item 2", "item 3"]

struct Item {
    let name: String
    let price: Int
}

let sortedItems = zip(names, prices).map(Item.init).sorted { $0.price < $1.price }

// [Item(name: "item 3", price: 1), Item(name: "item 2", price: 4), Item(name: "item 1", price: 9)]
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.