Javascript 在 word_number 键上有效地对字典(或 js 中的任何键值数据结构)进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10946880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:43:31  来源:igfitidea点击:

sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently

javascriptjquery

提问by user1054134

how do I sort a dictionary by key like

我如何按键对字典进行排序,例如

dict["word_21"] = "Hello Java";
dict["word_22"] = "Hello World";
dict["word_11"] = "Hello Javascript";

so that I get

所以我得到

dict["word_22"] = "Hello World";
dict["word_21"] = "Hello Java";
dict["word_11"] = "Hello Javascript";

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

只有索引上有 word_number 组合,值是字符串。索引是不同的(没有相等的值)但在错误情况下可能是“未定义的”

Edit: Actually I need the descending and ascending order of it. But the descending order is what I need at the moment.

编辑:其实我需要它的降序和升序。但降序是我目前需要的。

回答by Bergi

A javascript object, here used as a key-value-map (called "dictionary"), has no order; ie. you can't sort it.

这里用作键值映射(称为“字典”)的 javascript 对象没有顺序;IE。你不能排序。

You would need an array for that, e.g.

你需要一个数组,例如

[
    {id: "word_11", entry:"Hello Javascript"},
    {id: "word_21", entry:"Hello Java"},
    {id: "word_22", entry:"Hello World"},
]

then you could sort that byid or by entry. You might use your id-sort-algorithmfor that.

然后您可以id 或按条目对其进行排序。您可以为此使用您的 id-sort-algorithm



Or you could use an array of your keys to sort, next to the unsorted data structure. This might be the best (efficient) and simplest approach:

或者您可以在未排序的数据结构旁边使用一组键进行排序。这可能是最好(有效)和最简单的方法:

var dict = {
    "word_21": "Hello Java",
    "word_22": "Hello World",
    "word_11": "Hello Javascript"
}; // init (like your example)

var keys = Object.keys(dict); // or loop over the object to get the array
// keys will be in any order
keys.sort(); // maybe use custom sort, to change direction use .reverse()
// keys now will be in wanted order

for (var i=0; i<keys.length; i++) { // now lets iterate in sort order
    var key = keys[i];
    var value = dict[key];
    /* do something with key & value here */
} 

回答by Amberlamps

Try this

尝试这个

var sorted = [];
for(var key in dict) {
    sorted[sorted.length] = key;
}
sorted.sort();

Sorting dicton its keys and writing it back to the object does not make sense to me, but here it goes:

dict对其键进行排序并将其写回对象对我来说没有意义,但它是这样的:

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);

回答by sinclairzx81

If you just want to sort keys in an object, the following is fine (its a one liner)

如果您只想对对象中的键进行排序,则可以使用以下方法(单行)

/**
 * (typescript) returns the given object with keys sorted alphanumerically.
 * @param {T} obj the object to sort
 * @returns {T} the sorted object
 */
 const sort = <T extends object>(obj: T): T => Object.keys(obj).sort()
        .reduce((acc, c) => { acc[c] = obj[c]; return acc }, {}) as T

or the same in javascript

或在 javascript 中相同

/**
 * (javascript) returns the given object with keys sorted alphanumerically.
 * @param {T} obj the object to sort
 * @returns {T} the sorted object
 */
 const sort = (obj) => Object.keys(obj).sort()
        .reduce((acc, c) => { acc[c] = obj[c]; return acc }, {})

回答by Cybernetic

@Amberlamps nice solution works most of the time. But, the OP is correct that there are splitting issueswith certain keys. The default behavior of sort() in javascript is to use string Unicode code points to determine the order of the elements. For example, the following keys will notget sorted correctly using @Amberlamps method:

@Amberlamps 不错的解决方案大部分时间都有效。但是,OP 是正确的,某些键存在拆分问题。javascript 中 sort() 的默认行为是使用字符串 Unicode 代码点来确定元素的顺序。例如,使用@Amberlamps 方法将无法正确排序以下键:

canvas_2_1/15/2018__2:55:20_PM

canvas_24_1/15/2018__2:55:20_PM

But we can customize the sort method taking advantage of the fact that sort() accepts an optional argumentwhich is a functionthat compares 2 elements of the array.

但是我们可以利用 sort() 接受一个可选参数这一事实来自定义 sort 方法,该参数是一个比较数组的 2 个元素的函数

By customizing the sort logic of the compare function and passing it to the sort() method the keys above get sorted correctly:

通过自定义比较函数的排序逻辑并将其传递给 sort() 方法,上面的键可以正确排序:

sorted.sort(function(a, b) {
    a = parseInt(get_between(a, 'canvas_', '_'));
    b = parseInt(get_between(b, 'canvas_', '_'));
    if (a > b) {
        return 1;
    }
    if (b > a) {
        return -1;
    }
    return 0;
    });

In this case I'm using the following get_between method:

在这种情况下,我使用以下 get_between 方法:

function get_between(str, char_a, char_b) {
   res = str.split(char_a).pop().split(char_b).shift();
   return(res)
}

Th point is, if you have tricky keys (which may or may not be "proper" use of dict) you can adapt the sort function to still sort correctly.

这一点是,如果您有棘手的键(这可能是也可能不是 dict 的“正确”使用),您可以调整排序功能以仍然正确排序。

回答by Bruno Bronosky

Simply put, the dictionary type does not have a keys() method, while the Object type does. You can pass the Object.keys() method an iterable and get the keys back as a list which has a .sort() method.

简单地说,字典类型没有 keys() 方法,而 Object 类型有。您可以将 Object.keys() 方法传递给可迭代对象,并将键作为具有 .sort() 方法的列表取回。

Object.keys({r:2,d:2,c:3,p:0})
// returns ["r", "d", "c", "p"]
Object.keys({r:2,d:2,c:3,p:0}).sort()
// returns ["c", "d", "p", "r"]
Object.keys([6,7,8,9])
// returns ["0", "1", "2", "3"]

And finally, let's jsFiddle the OP's code.

最后,让我们jsFiddle OP 的代码

Update: Bergi's answer had too much going on and I totally missed the "good answer" part. I didn't even notice he did the same thing I did in my jsFiddle.

更新:Bergi 的回答太多了,我完全错过了“好答案”部分。我什至没有注意到他做了我在 jsFiddle 中做的同样的事情。