Split large Array in Array of two elements

前端 未结 7 1962
借酒劲吻你
借酒劲吻你 2020-12-20 17:53

I have large list of objects and I need to split them in a group of two elements for UI propouse.

Example:

[0, 1, 2, 3, 4, 5, 6]

Becomes

相关标签:
7条回答
  • 2020-12-20 18:29

    Alternatively, you can use reduce for this, but this is probably not the most efficient:

    let res = a.reduce([[Int]]()) { (var acc: [[Int]], current: Int) in
    
        if acc.last != nil && acc.last?.count < 2 {
            var newLast = acc.last
            newLast?.append(current)
            acc.removeLast()
    
            acc.append(newLast!)
        } else {
            acc.append([current])
        }
        return acc
    }
    
    0 讨论(0)
提交回复
热议问题