0

I have two arrays:

@State var myInterests: [String] = ["Beer", "Food", "Dogs", "Ducks"]
@State var otherInterests: [String] = ["Ducks", "Baseball", "Beer", "Pasta"]

I need to display a list with all shared interests listed first (top of the list), and then the others after.

ForEach(interests, id: \.self) { tag in
   Text(tag)
}

The result for otherInterests should be something like:

["Ducks", "Beer", "Baseball", "Pasta"]

Is there any way of sorting the array to move the shared interests to the front of the array and the remaining ones after?

Ryan
  • 155
  • 1
  • 14
  • This doesn't actually have anything to do with SwiftUI. You'll get more attention/traction to your question if you just ask about it in plain Swift terms (i.e. just remove the `@State`, `ForEach`, `Text`). I think this is a perfect fit for your problem: https://stackoverflow.com/a/43056896/3141234 – Alexander Aug 24 '22 at 21:25
  • Actually, this is an even better fit: https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md – Alexander Aug 24 '22 at 21:45

1 Answers1

2

As long as the order of the subitems is not that important (you can sort each sublist to make sure consistent output) - a simple solution can be to use sets here!

Something like this

let myInterests: [String] = ["Beer", "Food", "Dogs", "Ducks"]
let otherInterests: [String] = ["Ducks", "Baseball", "Beer", "Pasta"]
// This will result only in the shared interests between my and other
let sharedInterests = Set(myInterests).intersection(Set(otherInterests))
// This will result in only the not shared interests
let resetOfOtherInterest = Set(otherInterests).subtracting((Set(sharedInterests)))
// Here we combine the two (which are disjoint!)
let newOtherInterest = Array(sharedInterests) + Array(resetOfOtherInterest)

print(newOtherInterest)

newOtherInterest = ["Ducks", "Beer", "Baseball", "Pasta"]

CloudBalancing
  • 1,461
  • 2
  • 11
  • 22
  • 1
    Perhaps worth noting: this is an astable sorting algorithm. The relative positions between say "beer" and "ducks" won't be preserved – Alexander Aug 24 '22 at 21:26
  • Set object is an unordered collection type so the output won't always be the same – Omer Tekbiyik Aug 24 '22 at 21:26
  • True, But there was no definition on how to order the shared interest, a simple sort can do that... Nevertheless @Alexander comment on the question itself provide a solution, in case of keeping the original order it is preferable! – CloudBalancing Aug 24 '22 at 21:29
  • 1
    @CloudBalancing It might be fine, or it might not, it depends on OP's goals. Sorting the result can give a consistent output, but if keeping most of the original is what he's after, that order would be hard to "bring back" – Alexander Aug 24 '22 at 21:45
  • True that is why I considered your solution preferable – CloudBalancing Aug 24 '22 at 21:46