-3

I want to sort an array

like this:

let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]

I tried do this

var currentElement = ""
var newElements:[String] = []
for element in elements {
    if currentElement != element{
        currentElement = element
        newElements.append(element)
    }
}

but print["S", "A", "C", "T", "E", "F", "S", "A", "C"]

How to sort this to ["A","C","E","F","S","T"]

2
  • 1
    Wtf, you are not even sorting anything in your if condition, it's not even AN ATTEMPT to sort anything, you are just suppressing the duplicates ! Looks to me a lot like some kind of homework you don't want to do, get back to work and search on google. Commented Jun 6, 2018 at 8:21
  • 1
    First: Unique values: stackoverflow.com/questions/27624331/… Then sort: stackoverflow.com/questions/26719744/… Commented Jun 6, 2018 at 8:22

3 Answers 3

6
let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]

let sortedElements = elements.sorted(by: {$0 < $1})

print(sortedElements)

prints:

["A", "A", "A", "C", "C", "C", "E", "E", "E", "F", "S", "S", "S", "T"]
Sign up to request clarification or add additional context in comments.

Comments

3

What you want to do is to remove the duplicates and then sort it, right?

You can convert it to a Set, and then call sorted():

let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]
let newElements = Set(elements).sorted() // ["A", "C", "E", "F", "S", "T"]

Comments

0

You should use ComparisonResult to sort your array alphabetical, because Set(elements).sorted() and you have lowercase characters, the result of sort will be wrong.

var elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]

elements = elements.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

//the output["A", "A", "A", "C", "C", "C", "E", "E", "E", "F", "S", "S", "S", "T"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.