How can I order items in an object?

I want to count the number of occurrences of strings with node.js and started implementing a dictionary like below:

var dict = {}

// Example content ("string" = count)
dict["alpha"] = 12
dict["beta"] = 39

// Increment count (working)
dict["alpha"]++

      

But how do I sort this dictionary from highest to lowest? Is there any sort of built-in sorting or should I implement it myself?

I want to list the result from the highest to the lowest score in a file, with each line as follows:

<count> <string>

      

+3


source to share


3 answers


Continuing on Rob's answer, you can get the elements in a sorted array of objects having 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 an array of the form [{key: "alpha", value: 16}, ...]

which can then be converted to string using shorthand



var strToFile = res.reduce( function(p,n) { 
 return p + n.value+" "+n.key+"\n"; },"");

      

The result looks something like this:

39 beta
12 alpha

      

+2


source


Objects are unordered because keys are stored based on hash values. So, there is no such thing called sorting an object.

But you can just sort the keys based on count

and apply to it forEach

directly 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 figure it out, 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, for example

> temp.forEach(function(currentPair) {
...     console.log(currentPair[0], currentPair[1]);
... })
beta 39
alpha 12

      


Since you want to write the result to a 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 awesome answer to better understand how sorting is done in JavaScript.

+3


source


You can get an array of the words that occur most frequently (although you won't have any values ​​in the array);

Object.keys(dict).sort(function(a, b) { 
   return dict[b]-dict[a]; 
});
// ["beta", "alpha"]

      

0


source







All Articles