按频率列出数组中的对象,最常出现在第一个

时间:2016-08-16 20:35:57

标签: ios arrays swift parse-platform

我有几个数组,我附加到一个新的,更大的数组,并期待一些重复,我需要按频率列出的新的,更大的数组中的所有对象。

例如:

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

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

如何从bigArray创建一个新的数组,该数组按频率排序,从最多到最少,不重复,因此打印出来:

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

1 个答案:

答案 0 :(得分:2)

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}
print(result)
//["Parse", "iOS", "Swift"]