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
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
M.Warner
  • 25
  • 2
  • What is the type of `names`? is it array of strings? – Ahmad F Mar 29 '18 at 13:46
  • 2
    Are the indices in the seconds array always a permutation of the first arrays's indices? – Martin R Mar 29 '18 at 13:49
  • See also [Reorder array compared to another array in Swift](https://stackoverflow.com/questions/39273370/reorder-array-compared-to-another-array-in-swift). – Martin R Mar 29 '18 at 13:51

3 Answers3

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.

Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
d.felber
  • 5,288
  • 1
  • 21
  • 36
  • 1
    Simple and elegant. You don't even need the parentheses: `sorting.map { names[$0] }` – Tamás Sengel Mar 29 '18 at 13:51
  • 2
    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". – Ahmad F Mar 29 '18 at 13:53
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.

DionizB
  • 1,487
  • 2
  • 10
  • 20
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]
Community
  • 1
  • 1
Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36