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?
CodePudding user response:
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"]
CodePudding user response:
if you want to sort by keeping the order of the otherInterests
array , You can use below code ()
var myInterests: [String] = ["Beer", "Food", "Dogs", "Ducks"]
var otherInterests: [String] = ["Ducks", "Baseball", "Beer", "Pasta"]
var sortedIndexCount = 0
otherInterests = otherInterests.enumerated().reduce(into: [String]() ){
(result, element) -> Void in
result.append(element.element)
if !myInterests.contains(element.element)
{
sortedIndexCount = 1
}else{
result.remove(at: element.offset)
result.insert(element.element, at: sortedIndexCount)
}
}
print(otherInterests)
Output is :
["Ducks", "Beer", "Baseball", "Pasta"]
Im not sure to use
reduce
approach but it works