0

I'm wondering how to sort an array by another array in Swift 3

let's say I have :

struct Channel {
    var id: Int
}

let channel1 = Channel(id: 1)
let channel2 = Channel(id: 2)
let channel3 = Channel(id: 3)
let channel4 = Channel(id: 4)
let channel5 = Channel(id: 5)

var original = [channel1, channel2, channel3, channel4, channel5]
var favorites = [channel3, channel2, channel1, channel4]

and I want to sort the original array to be :

[channel3, channel2, channel1, channel4, channel5]

Is there any quick and low consuming way to do this ?

2 Answers 2

1
favorites.append(contentsOf: original.filter { chanel in
    !favorites.contains(where: { $0.id == chanel.id })
})
Sign up to request clarification or add additional context in comments.

1 Comment

Well, that was simple enough ! Thanks.
0

Zip is much easy method to achieve this

// use zip to combine the two arrays and sort that based on the first
// Your original array

let combined = zip(array1, array2).sort {$0.0 < $1.0}
print(combined) //  

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

Hope it helps

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.