1

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.

3
  • 5
    You can't sort objects. You can create an array of objects and sort it by using Array.prototype.sort method. Commented Nov 25, 2015 at 19:23
  • Another way to say it: there is no guarantee of the order of keys in an object Commented Nov 25, 2015 at 19:26
  • 2
    Object.keys(words).map(key => ( {key: key, count: words[key]} )).sort((a, b) => a.count - b.count); Commented Nov 25, 2015 at 19:30

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

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.