theGreenCabbage
theGreenCabbage

Reputation: 4845

Sorting Javascript associative array values in descending order

I have the following method that gets the word frequency based on some input text:

function getWordFrequency(lowerCaseArray) {
    var wordFrequency = {};
    $.each(lowerCaseArray, function(ix, word) {
        // skip empty results
        if (!word.length) {
        return;
        }
        // add word to wordFrequency
        if (!wordFrequency[word]) {
        wordFrequency[word] = 0;
        } 
        wordFrequency[word]++;
    });
    return wordFrequency;
}

However, I would like to return the frequency of words on a descending order, i.e.

cats => 20
dogs => 19
frog => 17
humans => 10

Currently, my algorithm returns in the order in which the input words appear.

Upvotes: 1

Views: 878

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

You have to return an array of objects if you want ordering. Properties of an object do not have a guaranteed order.

var obj = getWordFrequency(words);
var array = Object.keys(obj).map(function(key){
     return {word: key, count: obj[key]};
});
array.sort(function (a,b){ return b.count - a.count});

Typed from my phone, untested, order of a and b may need to be reversed

Upvotes: 2

Related Questions