NewToCoding February 2016

Order objects by occurrences

I have the following code which creates objects of each word (words that are in wordsArray) and checks for the number of occurrences of each word and stores this along with each object.

var wordOccurrences = { };
for (var i = 0, j = wordsArray.length; i < j; i++) {
        wordOccurrences[wordsArray[i]] = (wordOccurrences[wordsArray[i]] || 0) + 1;
}
console.log(wordOccurrences);

This outputs:

Object { hello: 1, world!: 2, click: 1, here: 1, goodbye: 1 }

I would appreciate if someone could help me with ordering the objects by their occurrences e.g. ascending or descending order. I have tried a few ways but none has yielded the correct results.

The desired output would be something like:

world! 2 
hello 1 
click 1 
here 1 
goodbye 1

Answers


A.J. February 2016

Try the following:

var wordOccurences = { "hello": 1, "world!": 2, "click": 1, "here": 1, "goodbye": 1 }
var sortable = [];
for (var word in wordOccurences)
      sortable.push([word, wordOccurences[word]])
sortable.sort(function(a, b) {return a[1] - b[1]}).reverse()
var result = {}
for(var i = 0; i < sortable.length; i++){
result[sortable[i][0]] = sortable[i][1]
}

console.log(result);


Nina Scholz February 2016

Just take an array for the keys and sort it.

var wordOccurrences = { hello: 1, 'world!': 2, click: 1, here: 1, goodbye: 1 },
    words = Object.keys(wordOccurrences).sort(function (a, b) {
        return wordOccurrences[b] - wordOccurrences[a] || a.localeCompare(b);
    });

document.write(words.map(function (a) {
    return a + ': ' + wordOccurrences[a];
}).join('<br>'));

Post Status

Asked in February 2016
Viewed 3,597 times
Voted 6
Answered 2 times

Search




Leave an answer