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?

8
  • 3
    You're asking an open-ended algorithm question - this might not do so well on SO. SO is meant for "I tried this. It's broken. I also tried this. What am I doing wrong?" type of questions. Commented May 22, 2018 at 12:44
  • I guess he wants something like grouping not sure if duplicate answer is same. Commented May 22, 2018 at 12:58
  • @TheTiger: Already reopened – I had misread the question, sorry about that! Commented May 22, 2018 at 12:59
  • @MartinR Oh my page was not refreshed. :) And I had the answer which now already has given by Abdelahad. Commented May 22, 2018 at 13:01
  • @TheTiger consider it your answer upvote it and get sportman badge Commented May 22, 2018 at 13:09

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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)")

Comments

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
}

1 Comment

Why return type is [Any] instead of [[String]] or Array<Array<String>> ?

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.