如何订购对象中的物品? [英] How can I order the items in an Object?
问题描述
我想用node.js计算字符串的出现次数,并开始实现如下所示的字典:
I want to count the number of occurrences of strings with node.js and started to implement 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 count? Is there any built in sorting or do I have to implement this myself?
我想列出文件中从最高计数到最低计数的输出,每行分别是:
I want to list the output from highest to lowest count in a file, with each line being:
<count> <string>
推荐答案
从Rob的答案继续,您可以将这些对象放入对象排序数组中,其值如下:
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
});
其中res是[{key:"alpha",value:16},...]形式的排序数组
Where res is sorted array of form [{key:"alpha",value:16},...]
然后可以使用reduce将哪些转换为字符串
Which can then be converted to string using reduce
var strToFile = res.reduce( function(p,n) {
return p + n.value+" "+n.key+"\n"; },"");
结果看起来像
39 beta
12 alpha
这篇关于如何订购对象中的物品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!