How Can I Order The Items In An Object?
Solution 1:
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) {
...returndict[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"] = 1212
> dict["beta"] = 3939
> 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) {
... returnpair2[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.
Solution 2:
Continuing from the Rob's answer, you could get the items in sorted array of objects having the values like this:
var res = Object.keys(dict).map(function(key ) {
return { key: key, value : dict[key] };
}).sort(function(a, b) {
return b.value - a.value
});
Where res is sorted array of form [{key:"alpha",value:16},...]
Which can then be converted to string using reduce
var strToFile = res.reduce( function(p,n) {
return p + n.value+" "+n.key+"\n"; },"");
The result looks something like
39 beta
12 alpha
Solution 3:
You could get the an array of the words that occur most frequently (though you won't have the values in the array);
Object.keys(dict).sort(function(a, b) {
return dict[b]-dict[a];
});
// ["beta", "alpha"]
Post a Comment for "How Can I Order The Items In An Object?"