Arrays of Int arrays. Storing duplicates in order only

后端 未结 6 1430
灰色年华
灰色年华 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 18:56

    You can use the forEach and keep the value of the last element to keep adding to your array while it's not different like in this way:

    let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]
    
    func filterTo2DArray(list: [Int] ) -> [[Int]] {
    
       var resultList = [[Int]]()
    
       list.forEach { x -> () in
          if let lastValue = resultList.last?.last where lastValue == x {
              resultList[resultList.count - 1].append(x)
          }
          else{
             resultList.append([x])
          }
       }
       return resultList
    }
    
    
    let t = filterTo2DArray(mainArray) //[[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]
    

    I hope this help you.

提交回复
热议问题