Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Items in an Array of Arrays?

Tags:

arrays

swift

If I have an object that is declared as

let compoundArray = [Array<String>]

is there a property that would give me the number of strings in all the arrays contained in compoundArray?

I can do it by adding up all the items in each array within:

var totalCount = 0
for array in compoundArray {
   totalCount += array.count }
//totalCount = total items in all arrays within compoundArray

But that seems clunky and it seems that swift would have a property/method of Array to do this, no?

Thanks!

like image 696
Jonathan Tuzman Avatar asked Jan 13 '17 09:01

Jonathan Tuzman


2 Answers

You can add the nested array counts with

let count = compoundArray.reduce(0) { $0 + $1.count }

Performance comparison for large arrays (compiled and run on a MacBook Pro in Release configuration):

let N = 20_000
let compoundArray = Array(repeating: Array(repeating: "String", count: N), count: N)

do {
    let start = Date()
    let count = compoundArray.joined().count
    let end = Date()
    print(end.timeIntervalSince(start))
    // 0.729196012020111
}

do {
    let start = Date()
    let count = compoundArray.flatMap({$0}).count
    let end = Date()
    print(end.timeIntervalSince(start))
    // 29.841913998127
}

do {
    let start = Date()
    let count = compoundArray.reduce(0) { $0 + $1.count }
    let end = Date()
    print(end.timeIntervalSince(start))
    // 0.000432014465332031
}
like image 176
Martin R Avatar answered Sep 19 '22 04:09

Martin R


You can use joined or flatMap for that.

Using joined

let count = compoundArray.joined().count

Using flatMap

let count = compoundArray.flatMap({$0}).count
like image 22
Nirav D Avatar answered Sep 20 '22 04:09

Nirav D