0

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
3
  • What is the type of names? is it array of strings? Commented Mar 29, 2018 at 13:46
  • 2
    Are the indices in the seconds array always a permutation of the first arrays's indices? Commented Mar 29, 2018 at 13:49
  • See also Reorder array compared to another array in Swift. Commented Mar 29, 2018 at 13:51

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Simple and elegant. You don't even need the parentheses: sorting.map { names[$0] }
Typical. Keep in mind that if the second sorting array contains a number that is not a valid index for the first array, you would get "Fatal error: Index out of range".
1

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.

2 Comments

Thank you for your quick help! Will try it
@dionizb Very elegant solution. +1
0

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]

2 Comments

Thank you for your help, will try it:
@Ankit please add some context regarding your answer, it will help for future readers.

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.