How to group items from array that match, into another array?

Viewed 385

For example say I have an array like so:

var someArray = ["1", "1", "2"]

I need to put this into two arrays that look like:

["1","1"]

["2"]

How can I go about this?

Any help would be great!

4 Answers

Use Dictionary initializer init(grouping:by:) Then just get arrays by accessing values property.

Example:

let dic = Dictionary(grouping: someArray) { $0 }
let values = Array(dic.values)
print(values)

Result:

[["2"], ["1", "1"]]

Here are some facts (the upvote and answer should go to @kirander)

With @kirander method's is using the Dictionary to map the objects in a O(N) runtime and O(N) memory.

The other solutions are mostly running in O(N*N) runtime and O(N) memory. Because of this, grouping a random array of 1000 items will take: 0.07s with @kirander solution and 34s. with other solutions.

func benchmark(_ title:String, code: ()->()) {
  let startTime = CFAbsoluteTimeGetCurrent()
  code()
  let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
  print("Time elapsed for \(title): \(timeElapsed) s.")
}

var array:[String] = []
for _ in 0...1000 {
  array.append("\(Int(arc4random_uniform(10)))")
}

// @kirander solution 0.07s
benchmark("Dictionary", code: {

  let dic = Dictionary(grouping: array, by: { $0 })
  let values = Array(dic.values)
})


// @Bruno solution ~34s
benchmark("Array", code: {
  var resultingArrays = [[String]]()
  for value in array {
    let ar = array.filter({ $0 == value })
    if !resultingArrays.contains(where: {$0 == ar}) {
      resultingArrays.append(ar)
    }
  }
})

You could try something like this:

var someArray = ["1", "1", "2"]

var resultingArrays = [[String]]()

for value in someArray {
    let array = someArray.filter({ $0 == value })
    if !resultingArrays.contains(where: {$0 == array}) {
        resultingArrays.append(array)
    }
}

You can try this one :

let arrM = ["1","3","4","6","1","1","3"]
let arrSrtd = Array(Set(arrM))
 for ele in arrSrtd{
   let a = arrM.filter( {$0 == ele})
    print(a)
}
Related