0

I have a list of URL and its respective favourite counts obtained from firebase database appended into an array of dictionaries as such:

dictionaryArray = [[1: URL1], [2: URL2], [1: URL3]]

I understand that we can sort the array of dictionaries by using .sort but that removes dictionaries with similar keys like in this case.

how do I sort it such that I get an array of the url ordered by their keys to this:

urlArray = [URL2, URL1, URL3] 

since URL2 has the higher key whereas URL1 and URL3 have similar keys

lws803
  • 907
  • 2
  • 10
  • 21
  • Possible duplicate of [Sort Dictionary by keys](http://stackoverflow.com/questions/25377177/sort-dictionary-by-keys) – Ahmad F Nov 22 '16 at 09:28
  • No no that doesn't explain what happens when there are duplicate keys. Ive tried that solution but it basically just removed the duplicates – lws803 Nov 22 '16 at 09:31
  • Sorting a collection will *never* remove entries. Can you show what you exactly tried? – Martin R Nov 22 '16 at 09:56

2 Answers2

2

You could use higher-order functions sorted and flatMap nested together like so:

let sortedURLs = dictionaryArray
                    .sorted(by: { $0.keys.first! > $1.keys.first! })
                    .flatMap({ $0.values.first! })

Note: watch out of forced unwrapped optionals it is working here but could lead to an exception

Thomas G.
  • 1,003
  • 12
  • 27
-1

You can sort by using sort descriptors available like below.

var descriptor: NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])
Parth Adroja
  • 13,198
  • 5
  • 37
  • 71