Jay Patel
Jay Patel

Reputation: 353

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

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"]

Upvotes: 4

Views: 1388

Answers (7)

Zalak Patel
Zalak Patel

Reputation: 1965

Please try this, hope it helps

var terms =  ["Hello","Me","That","Me","Hello","Me","as","the"]
var termFrequencies = [String: Int]()
for t in terms {
    if termFrequencies[t] == nil {
        termFrequencies[t] = 1
    } else {
        termFrequencies[t] = termFrequencies[t]! + 1
    }
}

for value in terms {
    let index = termFrequencies[value] ?? 0
    termFrequencies[value] = index + 1
}

let result = termFrequencies.sorted{$0.1 > $1.1}.map{$0.0}

Upvotes: 1

Prema Janoti
Prema Janoti

Reputation: 856

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
     }
   }
 }

Upvotes: 3

shafi
shafi

Reputation: 456

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)

Upvotes: 4

MjZac
MjZac

Reputation: 3536

This should work.

var array = ["Hello","Me","That","Me","Hello","Me","as","the"]
var tR : [String : Int] = [:]
let finalResult = array.reduce(tR) { result, item in
    var tArr : [String: Int] = result
    if let count = tArr[item] {
        tArr[item] = count+1
    } else {
        tArr[item] = 1
    }
    return tArr
    }
    .sorted(by: { item1, item2 in
        return item1.value > item2.value

    }).map() { $0.key }

Upvotes: 1

Sweeper
Sweeper

Reputation: 272760

This is what I have been able to come up with:

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

// record the occurences of each item
var dict = [String: Int]()
for item in array {
    if dict[item] == nil {
        dict[item] = 1
    } else {
        dict[item]! += 1
    }
}
// here I sort the dictionary by comparing the occurrences and map it so that the result contains only the key (the string)
let result = dict.sorted { $0.value > $1.value }.map { $0.key }

Upvotes: 2

Luciano van der Veekens
Luciano van der Veekens

Reputation: 6577

Loop through the array and maintain a word count dictionary. Make sure the dictionary can be sorted based on values and finally obtain the set of keys and transform it back into an array.

Upvotes: 1

Kula
Kula

Reputation: 25

It looks simple. 1. Take distinct from your array. 2. Make count according to distinct list. 3. Save results in collection - ie Dictionary. 4. Sort new collection.

Upvotes: 1

Related Questions