javascript - Order objects by occurrences -


i have following code creates objects of each word (words in wordsarray) , checks number of occurrences of each word , stores along each object.

var wordoccurrences = { }; (var = 0, j = wordsarray.length; < 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 appreciate if me ordering objects occurrences e.g. ascending or descending order. have tried few ways none has yielded correct results.

the desired output like:

world! 2  hello 1  click 1  here 1  goodbye 1 

try following:

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

console.log(result);


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -