Arrays of Int arrays. Storing duplicates in order only

后端 未结 6 1469
灰色年华
灰色年华 2021-01-11 18:37

I need to store an array of Int array for ordered duplicates (which are in a Array).

Example:

  • Given array:
    mainArray = [7, 7, 3, 2, 2, 2, 1,
6条回答
  •  醉酒成梦
    2021-01-11 19:03

    The following code will give you what you need...

    let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]
    var newArray: [[Int]] = []
    
    for var i=0; i < mainArray.count; i++ {
        let element = mainArray[i]
        if mainArray.indexOf(element) == i {
          var subArray = mainArray.filter({ $0 == element })
          newArray.append(subArray)
        }
    }
    
    print(newArray) // -> [[7, 7, 7], [3], [2, 2, 2], [1], [5, 5]]
    

提交回复
热议问题