Nassif
Nassif

Reputation: 1223

Split a list into two based on the filters in swift

Having a list of countries name, and if I search for a country that starts with B, how do I split the search with all the countries that begin with B as a list and the remaining countries as another list and then combine the both so that the countries with "B" is at the top

Upvotes: 0

Views: 194

Answers (3)

Tj3n
Tj3n

Reputation: 9943

You can also use Dictionary for splitting, it won't sort the key, but you got separated arrays to use:

let a = ["FF0000", "000000", "0083FF", "FBE58D", "7A9EB0", "909CE1"]
let b = Dictionary(grouping: a, by: { $0.first! })

print(b) //["0": ["000000", "0083FF"], "7": ["7A9EB0"], "F": ["FF0000", "FBE58D"], "9": ["909CE1"]]

Upvotes: 0

stackich
stackich

Reputation: 5287

Do you need it for a searchBar? If yes, try this:

let filteredCountries = CountriesArray.filter({ (country: String) -> Bool in
            return country.lowercased().contains(searchText.lowercased()) && country.hasPrefix(searchText)
        })

Also, for sorting try this:

let sortedArray =  filteredCountries.sorted(by: { $0.lowercased() < $1.lowercased() })

Even if you don't need it for a searchBar, explore filter() method, its very helpfull and easy to use.

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54755

You can use sorted(by:) to achieve your goals. You simply need to check if the current and the next element start with your search term using the prefix operator and in case the current element does start with it, but the next one doesn't, sort the current element before the next one, otherwise preserve current order.

extension Array where Element == String {
    /// Sorts the array based on whether the elements start with `input` or not
    func searchSort(input: Element) -> Array {
        sorted(by: { current, next in current.hasPrefix(input) && !next.hasPrefix(input) })
    }
}

["Austria", "Belgium", "Brazil", "Denmark", "Belarus"].searchSort(input: "B")

Output: ["Belgium", "Brazil", "Belarus", "Austria", "Denmark"]

Upvotes: 2

Related Questions