[英]How to sort array based on another arrays position?
I have a tableView
with its style being Right Detail
. 我有一个
tableView
,其风格是Right Detail
。 I therefore have 2 arrays
, one is for the textLabels
data, and the other is for detailTextLabel
. 因此,我有2个
arrays
,一个用于textLabels
数据,另一个用于detailTextLabel
。
There will be 2 "sort by" options. 将有2个“排序依据”选项。 One will be sort by the
textLabels
data, and the second will sort by the detailTextlabels
data. 一个将按
textLabels
数据排序,第二个将按detailTextlabels
数据排序。 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`. 因此,当我对第一个
array
( textLabels array
)进行排序时,第二个array (detailTextLables
数组) will also have to get sorted based on the first
数组) will also have to get sorted based on the first
。
I know how to sort arrays
, but how can I sort one array
based on another? 我知道如何对
arrays
进行排序,但是如何根据另一个array
对一个array
排序?
Here's how I sorted the array
: (it's an array
of Dates
. 这是我对
array
进行排序的方式:(这是Dates
array
。
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.
因为您只有一个UITableViewCell数组,并且您希望将与特定表视图单元关联的所有数据保持在一起。 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: 它有点乱,但您可以使用
enumerate
同时处理索引和元素:
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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.