0

How to count a number of time in array there are "Yes" ? In swift

["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]

For exemple here there are 3 times Thanks ;)

Jakub
  • 13,712
  • 17
  • 82
  • 139
Dan Boujenah
  • 51
  • 1
  • 4
  • What did you try and what went wrong ? – Wain Dec 14 '15 at 12:15
  • 3
    What have you tried so far? However, I do not think that this is some smart data structure. – Hermann Klecker Dec 14 '15 at 12:17
  • 1
    Possible duplicate of [How to count occurrences of an element in a Swift array?](http://stackoverflow.com/questions/30545518/how-to-count-occurrences-of-an-element-in-a-swift-array) – Armin Dec 14 '15 at 12:21
  • This can be done very simple with enumeration. Or do you want to do this in some smart functional-style way? – kelin Dec 14 '15 at 12:24
  • 1
    Possible duplicate of [Count number of items in an array with a specific property value](http://stackoverflow.com/questions/25398608/count-number-of-items-in-an-array-with-a-specific-property-value) – Nicolai Henriksen Mar 07 '17 at 20:41

4 Answers4

4

How about something like this?

//: Playground - noun: a place where people can play

import UIKit

let array = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let results = array.map({ $0.lowercaseString.containsString("yes") })
let count = results.filter({ $0 == true }).count
count // 3

You can also make it a one liner:

let count = array.filter({ $0.lowercaseString.containsString("yes") }).count 

Note: I also added a check for case sensitivity just incase the data source was inconsistent

liamnichols
  • 12,419
  • 2
  • 43
  • 62
2
let a = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let filtered = a.filter { (str) -> Bool in
    return str.containsString("Yes")
}
print(filtered.count)
chiarotto.alessandro
  • 1,491
  • 1
  • 13
  • 31
2
let array = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let count = array.reduce(0) { $0 + ($1.containsString("Yes") ? 1 : 0) }
count // 3
Lukas Kukacka
  • 7,604
  • 2
  • 25
  • 50
1

You can use NSPredicate to get required output like below

var arrayTemp = NSMutableArray(objects: "julien: Yes","elie: YES", "elie: NO", "Jean: Yes")
var predicate = NSPredicate(format: "self contains[cd] %@", "Yes")
arrayTemp.filterUsingPredicate(predicate)
print("COUNT===\(arrayTemp.count)")// 3 
Narayana Rao Routhu
  • 6,303
  • 27
  • 42