I have a string array as strList = ["12abc", "23bcd", "12shsh", "23xyz"] Is there any way to sort the array according to just first two characters of each string?
1 Answer
just try this
var strList = ["12abc", "23bcd", "12shsh", "23xyz","13das","21dadsd"]
var sortArray = strList.sorted()
debugPrint(strList)
print(sortArray)
the console result will show in below
["12abc", "23bcd", "12shsh", "23xyz", "13das", "21dadsd"]
["12abc", "12shsh", "13das", "21dadsd", "23bcd", "23xyz"]
2 Comments
Taohidur Imran
but if, strList = ["12shsh", "23bcd", "12abc", "23xyz","13das","21dadsd"] then the output will be 12shsh, 12abc..... So i need to sort by first 2 digit
Gereon
Note that you cannot rely on the order of same-sorted elements, since Swift's sort algorithm does not guarantee a stable sort.
prefix(2)strList.sorted()?.sort()or.sorted()results?sort(ed)by closure.