iProgram
iProgram

Reputation: 6547

How to arrange one dictionary array by ascending order and then reorder the other arrays?

I am trying to sort an dictionary (of type [String:[String]]) so that one key is in ascending order, once the key is sorted I would like to sort the other arrays too.

This is what I mean.

var dictionary = ["timeStamp":[String],"condition":[String]] //Dict to sort
dictionary["timeStamp"] = ["123","345","456","234"]
dictionary["condition"] = ["dry","wet","very wet","dry"]
dictionary["timeStamp"] = dictionary["timeStamp"]!.sort()
print("\(dictionary["timeStamp"]!)") //Returns["123","234","345","456"]

How would I be able to sort dictionary["condition"] to be ["dry","dry","wet","very wet"]?

Upvotes: 0

Views: 351

Answers (2)

Code Different
Code Different

Reputation: 93161

The preferred way is give it a proper structure like @Russel Austin suggested in his answer. But you can also have some fun with Swift higher-order functions:

var dictionary = [
    "timeStamp": ["123","345","456","234"],
    "condition": ["dry","wet","very wet","dry"]
]

let sorted = Array(0..<dictionary["timeStamp"]!.count)
    .map { (timeStamp: dictionary["timeStamp"]![$0], condition: dictionary["condition"]![$0]) }
    .sort { $0.timeStamp < $1.timeStamp }

dictionary["timeStamp"] = sorted.map { $0.timeStamp }
dictionary["condition"] = sorted.map { $0.condition }

print(dictionary)

Array(0..<dictionary["timeStamp"]!.count) generate an array of ints, going 0, 1, 2, 3... up to the length of timeStamp

.map { ... } pulls data from the dictionary into tuples of timestamp and condition

.sort{ ... } sorts the array of tuples by the timestamp

Upvotes: 0

Russell Austin
Russell Austin

Reputation: 409

I would make a simple struct so that your properties are associated and can be sorted together

struct condition {
    var timeStamp: Int
    var description: String
}

var conditionArray = [condition]()
conditionArray.append(condition(timeStamp: 123, description: "dry"))
conditionArray.append(condition(timeStamp: 345, description: "wet"))
conditionArray.append(condition(timeStamp: 456, description: "very wet"))
conditionArray.append(condition(timeStamp: 234, description: "dry"))
let sortedArray = conditionArray.sort() {return $0.timeStamp < $1.timeStamp}

Upvotes: 1

Related Questions