Objects are unordered, since the keys are stored based on the hash values. So, there is no such thing called sorting an Object.
But, you can simply sort the keys, based on the count
, and apply forEach
directly on it, like this
> Object.keys(dict).sort(function(key1, key2) {
... return dict[key2] - dict[key1];
... }).forEach(function(currentKey) {
... console.log(currentKey, dict[currentKey]);
... });
beta 39
alpha 12
To understand this, step-by-step you can convert the object to an array of pairs, like this
> var dict = {}
undefined
> dict["alpha"] = 12
12
> dict["beta"] = 39
39
> var temp = Object.keys(dict).map(function(currentKey) {
... return [currentKey, dict[currentKey]];
... });
undefined
> temp
[ [ 'alpha', 12 ],
[ 'beta', 39 ] ]
and then sort them based on the second element, with Array.prototype.sort
, like this
> temp.sort(function(pair1, pair2) {
... return pair2[1] - pair1[1];
... });
[ [ 'beta', 39 ],
[ 'alpha', 12 ] ]
And then print them as you like, like this
> temp.forEach(function(currentPair) {
... console.log(currentPair[0], currentPair[1]);
... })
beta 39
alpha 12
Since you want to write the result to the file, you can do it like this
> var fileWriter = require("fs").createWriteStream('Output.txt');
undefined
> Object.keys(dict).sort(function (key1, key2) {
... return dict[key2] - dict[key1];
... }).forEach(function (currentKey) {
... fileWriter.write(currentKey + " " + dict[currentKey] + "\n");
... });
undefined
> fileWriter.end();
undefined
> require("fs").readFileSync("Output.txt").toString()
'beta 39\nalpha 12\n'
You might want to go through this amazing answer, to better understand how sorting is done in JavaScript.