简体   繁体   中英

How to sort array based on another arrays position?

I have a tableView with its style being Right Detail . I therefore have 2 arrays , one is for the textLabels data, and the other is for detailTextLabel .

There will be 2 "sort by" options. One will be sort by the textLabels data, and the second will sort by the detailTextlabels data. So when I sort the first array ( textLabels array ), the second array (detailTextLables array ) will also have to get sorted based on the first array`.

I know how to sort arrays , but how can I sort one array based on another?

Here's how I sorted the array : (it's an array of Dates .

firstArray.sort({ (a, b) -> Bool in
    a.earlierDate(b) == a
})

First, why not have two arrays? Because you only have one array of UITableViewCells and you want to keep all the data associated with a particular table view cell together. And it makes the need to try to coordinate the sorting of multiple arrays (what you are asking to do) unnecessary.

But if you really want to do that:

var array1 = ["1", "3", "2"]
var array2 = ["One", "Three", "Two"]

let sortedFoo = zip(array1, array2).sort { $0.0 < $1.0 }

array1 = sortedFoo.map { $0.0 }
array2 = sortedFoo.map { $0.1 }

The idea with the above code is that it combines the two arrays into one array of tuples, and then sorts them based on the elements in the first array, then breaks that single array back out into two separate arrays.

In other words, since you have to combine the two arrays into one to do the sort anyway, you might as well make them in a single array in the first place. :-)

如何在排序数组上使用positionOf来查找I排序数组中的相应索引?

It's a bit messy, but you can use enumerate to work with indices and elements at the same time:

array1.enumerate().sort {
    return $0.element < $1.element
}.map {$0.element}

array1.enumerate().sort {
    return array2[$0.index] < array2[$1.index]
}.map {$0.element}

But it's really much simpler/easier with one array.

struct Item {
    let prop1: Int
    let prop2: String
}

var array = [
    Item(prop1: 1, prop2: "c"),
    Item(prop1: 2, prop2: "b"),
    Item(prop1: 3, prop2: "a")
]

array.sort { $0.prop1 < $1.prop1 }

array.sort { $0.prop2 < $1.prop2 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM