Search code examples
arraysswiftstringsorting

How to sort plus minus string start from biggest minus?


I want to sort array string of percent : ["-12.00%", "3.00%", "27.30%", "-8.37%"]

var array: [String]?
array = ["-12.00%", "3.00%", "27.30%", "-8.37%"]

I try with convert string to double then sort it with : array.sorted(by: { Double($0.string ?? "") ?? 0.0 < Double($1.string ?? "") ?? 0.0 }) but failed

The result that I want after sort is ["-12.00%", "-8.37%", "3.00%", "27.30%"]

How to sort with the result like I want, the biggest minus is on the lead until biggest plus is at the end?


Solution

  • The "%" symbol may be causing the problem. If it is always the last character then you could use .dropLast() to remove it.

    Then the function .sorted returns a new array, it doesn't sort the array in situ.

    Here is how these changes can be applied to your original attempt, assuming you start with an array of strings:

    let array = ["-12.00%", "3.00%", "27.30%", "-8.37%"]
    let sortedArray = array.sorted {
        (Double($0.dropLast()) ?? 0.0) < (Double($1.dropLast()) ?? 0.0)
    }
    print(sortedArray)
    
    ["-12.00%", "-8.37%", "3.00%", "27.30%"]