jwhubert91 jwhubert91 - 1 year ago 66
Swift Question

List objects in array by frequency with most frequently occurring first

I have several arrays that I am appending to a new, bigger array and expecting some repeats and I need all objects in the new, bigger array listed by frequency.

For example:

a = ["Swift","iOS", "Parse"]
b = ["Swift", "iOS", "Parse"]
c = ["iOS", "Parse"]
d = ["Parse"]

let bigArray:[String] = a+b+c+d

How can I create a new array from bigArray that is sorted by frequency from most to least without repeats, so it prints:

["Parse", "iOS", "Swift"]

Answer Source
let a = ["Swift","iOS", "Parse"]
let b = ["Swift", "iOS", "Parse"]
let c = ["iOS", "Parse"]
let d = ["Parse"]

var dictionary = [String: Int]()

for value in a+b+c+d {
    let index = dictionary[value] ?? 0
    dictionary[value] = index + 1

let result = dictionary.sort{$0.1 > $1.1}.map{$0.0}
//["Parse", "iOS", "Swift"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download