Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array alphabetically with number

Tags:

ios

swift

myArray = [Step 6, Step 12, Step 5, Step 14, Step 4, Step 11, Step 16, Step 9,  Step 3, Step 13, Step 8, Step 2, Step 10, Step 7, Step 1, Step 15] 

How can I sort this array above in this way?

[Step 1, Step 2, Step 3, Step 4, ....] 

I used this function in swift sort(&myArray,{ $0 < $1 }) but it was sorted this way

[Step 1, Step 10, Step 11, Step 12, Step 13, Step 14, Step 15, Step 16, Step 2,   Step 3, Step 4, Step 5, Step 6, Step 7, Step 8, Step 9] 
like image 888
Dennis Garcia Avatar asked Jul 03 '15 14:07

Dennis Garcia


People also ask

How do I sort an array alphabetically?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

How do you sort a number in an array of strings?

Using the Arrays.util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity is O(n log(n)). It is a static method that parses an array as a parameter and does not return anything.


1 Answers

Another variant is to use localizedStandardCompare:. From the documentation:

This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate.

This will sort the strings as appropriate for the current locale. Example:

let myArray = ["Step 6", "Step 12", "Step 10"]  let ans = sorted(myArray,{ (s1, s2) in      return s1.localizedStandardCompare(s2) == NSComparisonResult.OrderedAscending })  println(ans) // [Step 6, Step 10, Step 12] 

Update: The above answer is quite old and for Swift 1.2. A Swift 3 version is (thanks to @Ahmad):

let ans = myArray.sorted {     (s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending } 

For a different approach see https://stackoverflow.com/a/31209763/1187415, translated to Swift 3 at https://stackoverflow.com/a/39748677/1187415.

like image 181
Martin R Avatar answered Oct 13 '22 01:10

Martin R