How do I add the count from different arrays

How do I add the count from two different arrays?

array1 has 5 objects
array2 has 2 objects

How do I get the sum from both arrays since I am looking at the number of objects?

Thank you in advance for your help!

@jport1130 Thanks very much for your question!

From the Apple documentation, we see that the count method of Array returns an Int. So you could do something like the following:

// Initialize the Arrays
var array1 = [1,2,3, 4, 5]
var array2 = [1,2]

// Get the size of the array
let count1 = array1.count
let count2 = array2.count

// Sum the two numbers
var sum = count1 + count2
print(sum) 

I hope this helps!
All the best!

Thank you for the response. I have tried this and it works with numbers within an array but I am just counting the number of objects in the array. Sorry I am new to this so hopefully I am explaining it correctly.

@jport1130 I understand. My code above is counting the number of objects, but not the numbers in the array themselves. If you change the contents of the array to Strings, you’ll get the same answer.

Sorry I was editing my response as you answered. I just need to figure out how to cycle through my arrays and add them together but now I understand what you are saying. Basically I have an array within and array and I can get the count, but haven’t been able to add them together.

@jport1130 I think I now understand what you’re saying. Here is something you can do:

let arrayInArray = [[1, 2, 3], [4, 5, 6, 7]]
let flattenedArray = arrayInArray.flatMap{$0}
// flattenedArray = [1, 2, 3, 4, 5, 6, 7]
let sum = flattenedArray.count

This is a good opportunity for you to learn the FlatMap function in Swift (and while you’re at it, learn Map, Filter, and Reduce as well). :slight_smile:

I hope this helps!

All the best!

That makes sense. What is the best way to get my arrays into the arrayInArray? I was trying a “for” statement

for item in estimatelist.takeOffList {

}

I am trying to count the combined items in Array2 below. Which would result in 4 [[A,B,C], [A]]
Array1
Item 1
Array2
Item A
Item B
Item C
Item 2
Array2
Item A

@syedfa If you don’t have that many, you can simply do:

arrayInArray.append(array1)

Thank you for your help! I’m just to new at this :slight_smile: so I am trying to figure it out.

This topic was automatically closed after 166 days. New replies are no longer allowed.