2016-08-16 153 views
0

我有幾個陣列,我正在追加到一個新的更大的陣列,並期待一些重複,我需要按頻率列出的新陣列中的所有對象。列出按頻率排列的對象,頻率最高的頻率

例如:

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

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

如何創建從bigArray一個新的數組,它是通過頻率從最分類到至少不重複的,因此它打印:

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

回答

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"]