0

I am facing a problem with array sorting.
I am trying to sort an array, but not getting the result as expected. If I want to sort when the count are the same, they also get sorted by price.
What's wrong with my approach?

self.array = items.sorted(by: { (item1, item2) -> Bool in 
                 if item1.count > item2.count {                      
                    return true                  
                 } else {                      
                    if item1.count == item2.count {
                        if item1.price > item2.price {
                            return true
                        }
                    }
                 }              
                return false
             })

this is my sort result:

[Item(name: "AAA", count: 7, price: "30737517", index: 0), 
 Item(name: "EEE", count: 3, price: "8814388", index: 4), 
 Item(name: "CCC", count: 3, price: "12100396", index: 2), 
 Item(name: "DDD", count: 1, price: "9403300", index: 3), 
 Item(name: "FFF", count: 1, price: "5072755", index: 5), 
 Item(name: "BBB", count: 1, price: "21477775", index: 1)]

When the count numbers are same, I want to sort the array by price in descending order.

1
  • price is a String I guess? Then, tell me: if you compare: "BBB" and "BBABBB", which one will be "first"? How is the comparison between Strings done? Compare characters at 0, then compare characters at 1, then compare characters at 2, etc. How is a Int compare? If you compare 10 and 2, is that the same logic? No. Transform the price into a Int or a Double. Maybe use it into your struct too as such. Commented Jan 7, 2019 at 7:26

2 Answers 2

1

Lexically is 10 greater than 2 but "10" is less than "2"

There are APIs to sort strings numerically

self.array = items.sorted { ($0.count >= $0.count) && $0.price.compare($1.price, options: .numeric) == .orderedAscending }

or

self.array = items.sorted { ($0.count >= $0.count) && $0.price.localizedStandardCompare($1.price) == .orderedAscending }
Sign up to request clarification or add additional context in comments.

Comments

0

Probably you would want to make your price become Int or Double in your struct or class, String comparison only compare the first character so "8814388" > "12100396", this conversion should work:

self.array = items.sorted(by: { ($0.count >= $1.count) && (Double($0.price) ?? 0 > Double($1.price) ?? 0) })

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.