Reputation: 55
I have an array like below:
let totalArr = ["First","Second","Third","Fourth","First","Second", "Second"]
My Required output is:
let grouper = [["First","First"],["Second", "Second", "Second"],["Third"], ["Fourth"]]
can anybody give optimal iterations?
Upvotes: 1
Views: 1890
Reputation: 265
try this :)
You can pass any String array to the function and it will return your desired result:
func groupArr(totalArr: [String]) -> [Any]{
var grouperArr = [[String]]()
for i in totalArr{
let arr = totalArr.filter({($0 == i)}) as [String]
if(grouperArr.contains(arr) == false){
grouperArr.append(arr)
}
}
return grouperArr
}
Upvotes: 3
Reputation: 6067
let totalArr = ["First","Second","Third","Fourth","First","Second", "Second"]
let grouper = (Dictionary(grouping: totalArr, by: { $0})).map { $0.value}
print(grouper)
or
let arranged = (Dictionary(grouping: totalArr, by: { $0})).values
print(arranged)
Upvotes: 6
Reputation: 427
You can use Dictionay's grouping function to make a group and then get all values.
let totalArr = ["First","Second","Third","Fourth","First","Second", "Second"]
let group = Dictionary(grouping: totalArr) { (object) -> String in
let lowerBound = String.Index(encodedOffset: 0)
let upperBound = String.Index(encodedOffset: 1)
return String(object[lowerBound...upperBound])
}
print("group :\(group.values)")
Upvotes: 3