Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of items in an array with a specific property value

Tags:

I have a Person() class:

class Person : NSObject {      var firstName : String     var lastName : String     var imageFor : UIImage?     var isManager : Bool?      init (firstName : String, lastName: String, isManager : Bool) {         self.firstName = firstName         self.lastName = lastName         self.isManager = isManager     } } 

I have an array of Person()

var peopleArray = [Person]() 

I want to count the number of people in the array who have

 isManager: true 

I feel this is out there, but I can;t find it, or find the search parameters.

Thanks.

like image 750
Nate Birkholz Avatar asked Aug 20 '14 07:08

Nate Birkholz


People also ask

How do you count the number of items in an array?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

How do you count items in an array in Python?

Python len() method enables us to find the total number of elements in the array/object. That is, it returns the count of the elements in the array/object.


1 Answers

Use filter method:

let managersCount = peopleArray.filter { (person : Person) -> Bool in     return person.isManager! }.count 

or even simpler:

let moreCount = peopleArray.filter{ $0.isManager! }.count 
like image 72
Michał Ciuba Avatar answered Oct 01 '22 08:10

Michał Ciuba