1

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?

TheTiger
  • 13,264
  • 3
  • 57
  • 82
RSP
  • 53
  • 6

3 Answers3

6
 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)
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
3

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
}
Gaurav Bharti
  • 1,065
  • 1
  • 14
  • 22
Abhay Singh
  • 255
  • 1
  • 8
3

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)")
Malleswari
  • 427
  • 3
  • 11