How can I sort multiple arrays based on the sorted order of another array

前端 未结 2 1158
情深已故
情深已故 2020-12-01 23:22

I have multiple arrays, and I want to sort all of them based on the sorted order of one of them, like so:

var myArr = [\"b\", \"a\", \"c\"]
var myArr2 = [\"l         


        
2条回答
  •  感动是毒
    2020-12-01 23:35

    From what I understand, you want to order your array alphabetically. If so, you can use one of the example below :

    Example 1

    var anArray1 = ["b","a","d","e","c"]
    
    func alphabeticallyOrder(lt : String, rt: String) -> Bool {
        return lt < rt
    }
    
    anArray1 = sorted(anArray1, alphabeticallyOrder)
    
    println(anArray1) // [a, b, c, d, e]
    

    Example 2

    var anArray2 = ["b","a","d","e","c"]
    
    anArray2 = sorted(anArray2, {$0 < $1})
    
    println(anArray2) // [a, b, c, d, e]
    

    Example 3

    var anArray3 = ["b","a","d","e","c"]
    
    anArray3 = sorted (anArray3 , <)
    
    println(anArray3) // [a, b, c, d, e]
    

    Edit : My bad, you also want to change the other arrays indexes in the process. I'll edit later if required.

提交回复
热议问题