简体   繁体   English

按underscore.js中的键排序

[英]Sorting by keys in underscore.js

I have one dictionary: 我有一本字典:

{
    abc : {id : 1},
    defg : {id : 2}
}

I want to sort dictionary by keys length using underscore.js Output like: 我想使用underscore.js按键长度对字典进行排序,如下所示:

{
    defg : {id : 2},
    abc : {id : 1}
}

Prototype work: http://jsfiddle.net/UCWL2/71/ 原型作品: http//jsfiddle.net/UCWL2/71/

Dictionary, which is a plain JS object, can't be reliably sorted, because the order of elements isn't specified by the ECMA Script 5 spec. 由于是ECMA Script 5规范未指定元素的顺序,因此字典(它是普通的JS对象)无法可靠地排序。 Of course, you might rely on the browser-specific behaviour, but that isn't guaranteed to be the same accross browsers, their versions etc. 当然,您可能会依赖于特定于浏览器的行为,但这并不能保证浏览器,其版本等都相同。

If you need sorted maps, you'd want to use arrays (but then you lose the log(n) access complexity), or some 3rd party library for that (ie dsjslib ). 如果需要排序的映射,则需要使用数组(但是这样会丢失log(n)访问复杂性),或者使用一些第三方库( 例如dsjslib )。

var avatars = [
    {idx: 102, userInfo: {buddy_name: 'Avatar102', is_online: 1}},
    {idx: 100, userInfo: {buddy_name: 'Avatar100', is_online: 1}},
    {idx: 101, userInfo: {buddy_name: 'Avatar101', is_online: 1}}
];

avatars = _(avatars).sortBy(function(avatar) {
    return -avatar.idx;// -ve is put in front of variable to sort in desc i.e reverse direction
});
console.log(JSON.stringify(avatars));

Just replace return avatar.idx;//.userInfo.buddy_name; 只需替换return avatar.idx; //。userInfo.buddy_name; by return -avatar.idx;//.userInfo.buddy_name; 通过返回-avatar.idx; //。userInfo.buddy_name; it reverses the result. 它会反转结果。

Working jsfiddle : http://jsfiddle.net/0Lb44h96/ 工作jsfiddle: http : //jsfiddle.net/0Lb44h96/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM