How to group elements from an array that match into another array?

For example, I have an array like this:

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

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

["1","1"]

["2"]

How can i do this?

Any help would be great!

+4
source share
4 answers

Use the init initializer dictionary (grouping: by :) Then just get the arrays by accessing the value properties.

Example:

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

Result:

[["2"], ["1", "1"]]
+6
source

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

Using the @kirander method, it is used Dictionaryto match objects in O(N) runtimeand O(N) memory.

O(N*N) runtime O(N) memory. - 1000 : 0,07 @kirander 34s. .

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)
    }
  }
})
+4

You can 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)
    }
}
+1
source

You can try the following:

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)
}
-3
source

Source: https://habr.com/ru/post/1689556/


All Articles