Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array according to number of occurrence of string?

Tags:

swift

How to sort array according to number of occurrence of string

Example : var array = ["Hello","Me","That","Me","Hello","Me","as","the"]

and sorted array should be like this

["Me","Hello","That","as","the"]

like image 442
Jay Patel Avatar asked Oct 27 '25 10:10

Jay Patel


2 Answers

Updated For Swift 3

var array = ["Hello","Me","That","Me","Hello","Me","as","the"]

            var counts:[String:Int] = [:]

            for item in array {
                counts[item] = (counts[item] ?? 0) + 1
            }
            print(counts)

            let result = counts.sorted { $0.value > $1.value }.map { $0.key }
            print(result)

            array.removeAll()
            for string in result {
                array.append(string)
            }
            print(array)
like image 88
shafi Avatar answered Oct 29 '25 01:10

shafi


Try this -

It is tested and working as expected --

 let arrayName = ["Hello","Me","That","Me","Hello","Me","as","the"]
    var counts:[String:Int] = [:]
    for item in arrayName {
        counts[item] = (counts[item] ?? 0) + 1
    }

   let array = counts.keysSortedByValue(isOrderedBefore: >)
   print(array) // Output - ["Me", "Hello", "the", "That", "as"]

Create Dictionary extension -

extension Dictionary {
func sortedKeys(isOrderedBefore:(Key,Key) -> Bool) -> [Key] {
    return Array(self.keys).sorted(by: isOrderedBefore)
}

// Faster because of no lookups, may take more memory because of duplicating contents
func keysSortedByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
    return Array(self)
        .sorted() {
            let (_, lv) = $0
            let (_, rv) = $1
            return isOrderedBefore(lv, rv)
        }
        .map {
            let (k, _) = $0
            return k
     }
   }
 }
like image 26
Prema Janoti Avatar answered Oct 29 '25 02:10

Prema Janoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!