有效地对word_number键上的字典(或js中的任何键值数据结构)进行排序 [英] sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently
本文介绍了有效地对word_number键上的字典(或js中的任何键值数据结构)进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何按键对词典进行排序,如
how do I sort a dictionary by key like
dict["word_21"] = "Hello Java";
dict["word_22"] = "Hello World";
dict["word_11"] = "Hello Javascript";
因此我得到
dict["word_22"] = "Hello World";
dict["word_21"] = "Hello Java";
dict["word_11"] = "Hello Javascript";
索引上只有word_number组合,值是字符串。索引是不同的(没有相等的值)但在错误情况下可能是未定义的
There are word_number combinations on indices only and the values are strings. The indices are distinct (no equal values) but could be "undefined" in an error case
编辑:实际上我需要它的降序和升序。但降序是目前我需要的。
Actually I need the descending and ascending order of it. But the descending order is what I need at the moment.
推荐答案
试试这个
var sorted = [];
for(var key in dict) {
sorted[sorted.length] = key;
}
sorted.sort();
在其键上排序 dict
并编写回到对象对我来说没有意义,但在这里:
Sorting dict
on its keys and writing it back to the object does not make sense to me, but here it goes:
function sortOnKeys(dict) {
var sorted = [];
for(var key in dict) {
sorted[sorted.length] = key;
}
sorted.sort();
var tempDict = {};
for(var i = 0; i < sorted.length; i++) {
tempDict[sorted[i]] = dict[sorted[i]];
}
return tempDict;
}
dict = sortOnKeys(dict);
这篇关于有效地对word_number键上的字典(或js中的任何键值数据结构)进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文