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 firstarray`.

  • iOS8 Auto layout programatically pin to relative layout margin
  • How to draw a “speech bubble” on an iPhone?
  • Turn a page like a Book with UIView?
  • starting ios project without storyboard
  • Crop letter from image using Masking
  • Will download resume after closing my app in Background Mode
  • 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

    3 Solutions Collect From Internet About “How to sort array based on another arrays position?”

    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 }

    How about using using positionOf on the sorted array to find the corresponding index in the I sorted array?

    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 = { $0.0 }
    array2 = { $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. 🙂