Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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%"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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%"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading