23

In Swift, say I have two arrays:

var array1: [Double] = [1.2, 2.4, 20.0, 10.9, 1.5]
var array2: [Int] = [1, 0, 2, 0, 3]

Now, I want to sort array1 in ascending order and reindex array2 accordingly so that I get

array1 = [1.2, 1.5, 2.4, 10.9, 20.4]
array2 = [1, 3, 0, 0, 2]

Is there a simple way to do this using Swift functions or syntax?

I know I can build a function to do it and can keep track of indices, but I'm curious if there is a more elegant solution.

3

4 Answers 4

50
let array1: [Double] = [1.2, 2.4, 20.0, 10.9, 1.5]
let array2: [Int] = [1, 0, 2, 0, 3]

// use zip to combine the two arrays and sort that based on the first    
let combined = zip(array1, array2).sorted {$0.0 < $1.0}
print(combined) // "[(1.2, 1), (1.5, 3), (2.4, 0), (10.9, 0), (20.0, 2)]"

// use map to extract the individual arrays    
let sorted1 = combined.map {$0.0}
let sorted2 = combined.map {$0.1}

print(sorted1)  // "[1.2, 1.5, 2.4, 10.9, 20.0]"
print(sorted2)  // "[1, 3, 0, 0, 2]"

Sorting more than 2 arrays together

If you have 3 or more arrays to sort together, you can sort one of the arrays along with its offsets, use map to extract the offsets, and then use map to order the other arrays:

let english = ["three", "five", "four", "one", "two"]
let ints = [3, 5, 4, 1, 2]
let doubles = [3.0, 5.0, 4.0, 1.0, 2.0]
let roman = ["III", "V", "IV", "I", "II"]

// Sort english array in alphabetical order along with its offsets
// and then extract the offsets using map
let offsets = english.enumerated().sorted { $0.element < $1.element }.map { $0.offset }

// Use map on the array of ordered offsets to order the other arrays
let sorted_english = offsets.map { english[$0] }
let sorted_ints = offsets.map { ints[$0] }
let sorted_doubles = offsets.map { doubles[$0] }
let sorted_roman = offsets.map { roman[$0] }

print(sorted_english)
print(sorted_ints)
print(sorted_doubles)
print(sorted_roman)

Output:

["five", "four", "one", "three", "two"]
[5, 4, 1, 3, 2]
[5.0, 4.0, 1.0, 3.0, 2.0]
["V", "IV", "I", "III", "II"]
8
  • 1
    [+1] I rather went the long way round with creating tuples manually in my answer - using zip is much nicer!
    – Stuart
    Commented Nov 8, 2015 at 2:03
  • @Stuart, your idea is the same as mine. Your manual method would come in handy for more arrays or more complex situations. I was going to up vote your answer.
    – vacawama
    Commented Nov 8, 2015 at 2:15
  • Thanks, I just (obviously) preferred your more concise solution! I’ve reinstated my answer anyway, in case the long solution is helpful to anybody in different situations.
    – Stuart
    Commented Nov 8, 2015 at 11:20
  • @vacawama, here we are sorting array1 and corresponding array2 is sorted. Is there any way that array1 remains as is and array2 is sorted in that order? For instance array1 = [2,1,3], array2 = [3,1,2, 4] sortedArray2 = [2,1,3, 4]
    – Ankur Arya
    Commented Jun 14, 2017 at 10:59
  • @TheDoctor, you could use paired elements of sorted1 and sorted2 to create a dictionary and then use map on the original array1 to create the new array2.
    – vacawama
    Commented Jun 14, 2017 at 11:10
7

You could "link" the items of each array by mapping over the indices to create an array of tuples, then sort the tuples according to the first array's values before extracting the original arrays.

assert(array1.count == array2.count, "The following technique will only work if the arrays are the same length.")
let count = array1.count

// Create the array of tuples and sort according to the
// first tuple value (i.e. the first array)
let sortedTuples = (0..<count).map { (array1[$0], array2[$0]) }.sort { $0.0 < $1.0 }

// Map over the sorted tuples array to separate out the
// original (now sorted) arrays.
let sortedArray1 = sortedTuples.map { $0.0 }
let sortedArray2 = sortedTuples.map { $0.1 }
0
5

Swift 4

This part is translated from @vacawama's answer to Swift 4 syntax

let array1: [Double] = [1.2, 2.4, 20.0, 10.9, 1.5]
let array2: [Int] = [1, 0, 2, 0, 3]

// use zip to combine the two arrays and sort that based on the first    
let combined = zip(array1, array2).sorted(by: {$0.0 < $1.0})
print(combined) // "[(1.2, 1), (1.5, 3), (2.4, 0), (10.9, 0), (20.0, 2)]"

// use map to extract the individual arrays    
let sorted1 = combined.map {$0.0}
let sorted2 = combined.map {$0.1}

print(sorted1)  // "[1.2, 1.5, 2.4, 10.9, 20.0]"
print(sorted2)  // "[1, 3, 0, 0, 2]"

The above logic can be expanded for three or more arrays:

(slow)

let array1: [Double] = [1.2, 2.4, 20.0, 10.9, 1.5]
let array2: [Int] = [1, 0, 2, 0, 3]
let array3: [Float] = [3.3, 1.1, 2.5, 5.1, 9.0]

// use zip to combine each (first, n.th) array pair and sort that based on the first    
let combined12 = zip(array1, array2).sorted(by: {$0.0 < $1.0})
let combined13 = zip(array1, array3).sorted(by: {$0.0 < $1.0})

// use map to extract the individual arrays    
let sorted1 = combined12.map {$0.0}
let sorted2 = combined12.map {$0.1}
let sorted3 = combined13.map {$0.1}

As @Duncan C pointed out, this approach is not very efficient as the first array is sorted repeatedly. @vacawama's approach should be used instead, which in Swift 4 syntax is:

(fast)

let offsets = array1.enumerated()sorted(by: {$0.element < $1.element}).map {$0.offset}
let sorted1 = offsets.map {array1[$0]}
let sorted2 = offsets.map {array2[$0]}
let sorted3 = offsets.map {array3[$0]}
3
  • 1
    This approach would work, but you are sorting the "key" array repeatedly for each extra array. vacawama's approach of using enumerated() to get indexes for each item in the keys array and then use the array of sorted indexes to sort all the other arrays would be faster than sorting the keys array repeatedly.
    – Duncan C
    Commented Jul 12, 2018 at 1:42
  • Your approach would probably take O(x•n log(n) ) time (Where n is the number of items in teach array, and x is the number of arrays.) vacawama's approach would probably take O(n log(n) ) time, since he's only sorting the array of keys once. (I say probably because I'm not sure of the time complexity of the Swift standard library's sorted() function, but n • log(n) time complexity is good for a sorting algorithm.
    – Duncan C
    Commented Jul 12, 2018 at 1:42
  • You're right @Duncan C, vacawama's approach is more efficient. I edited my answer.
    – QitVision
    Commented Jul 12, 2018 at 8:58
0

Though not especially elegant, a simple solution when working with arrays of objects which must be compared, and whose orders are not known and may not even share the same lengths, is to loop the "ordered" array, finding the matching object in the unordered array, and appending it to a new empty array:

var sorted: [Foo] = []

// Loop the collection whose order will define the other
for item in originalOrder {
    // Find the item in the unsorted collection
    if let next = unsortedItems.first(where: { $0 === item }) {
        // Move the item to the new collection, thus achieving order parity
        sorted.append(next)
    }
}

This is useful when you have an operation that provides a transformed version of a collection which may have 0..<original.count number of items in any order, and you want to get back to the original order using pointer/object equality.

If you need to additionally maintain index parity, you can skip the if let and just append the result of first(where:) directly into sorted, which will put nil into the blanks.

Note that this example solution will additionally act as a filter for items which are either duplicated or not in the original, which may or may not be what you want. Modify to your needs.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.