M.Warner
M.Warner

Reputation: 25

Sort String array by Int Array

I want to order an array with the help of another, like this:

var names = [anna, berta, caesar, dora]
var sorting = [2, 0, 1, 3]

to be sorted like this:

var sortedNames = [caesar, anna, berta, dora]

so that the Integer array ("sorting") sorts the String array ("names") after its own values. How can I do that?

I tried it with a for loop, but it didn't worked.

for i in 0...names.count
{
    let x = "\(names[sorting]])"

    sortedNames.append(x)
}
return history

Upvotes: 0

Views: 145

Answers (3)

d.felber
d.felber

Reputation: 5408

You can use the map() function to transform the values of sorting:

var names = ["anna", "berta", "caesar", "dora"]
var sorting = [2, 0, 1, 3]

let sortedNames = sorting.map({ names[$0] }) // ["caesar", "anna", "berta", "dora"]

Keep in mind that this solution only works if the values in sorting are valid indices for the names array.

Upvotes: 6

Ankit Jayaswal
Ankit Jayaswal

Reputation: 5679

var names = [anna, berta, caesar, dora]

var sorting = [2, 0, 1, 3]

Simple approach with for loop is to select the values from sorting array and treat them as index to get respective value from names array.

var sortedNames = [String]()
for i in 0..<sorting.count {
    let x = sortedNames[i]
    sortedNames.append(x)
}   
return sortedNames // [caesar, anna, berta, dora]

Upvotes: 0

DionizB
DionizB

Reputation: 1507

You can create a new object which has properties the names and sorting

var name: String!
var sorting: Int!

Then you can easily sort your array of objects like this

array.sort(by: {$0.sorting<$1.sorting})

In this way you will have for each name sorting value and it will be pretty easy to do any manipulations with it.

Upvotes: 1

Related Questions