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

3
  • Possible duplicate of Sort Dictionary by keys Commented Nov 22, 2016 at 9: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 Commented Nov 22, 2016 at 9:31
  • Sorting a collection will never remove entries. Can you show what you exactly tried? Commented Nov 22, 2016 at 9:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.