使用underscorejs进行多维排序

问题描述 投票:0回答:2

我的json结构如下;

var MyJson = 

[   
    {
        "Country": "Austria",
        "SubCategory": "55",
    }, {
        "Country": "Brazil",
        "SubCategory": "0",
    }, {
        "Country": "Canada",
        "SubCategory": "25",
    }, {
        "Country": "Cyprus",
        "SubCategory": "55",
    },  {
        "Country": "Denmark",
        "SubCategory": "0",
    }, {
        "Country": "France",
        "SubCategory": "25",
    }, {
        "Country": "Greece",
        "SubCategory": "55",
    }, {
        "Country": "Hungary",
        "SubCategory": "0",
    }
];

我正在整理如下;

_.sortBy(MyJson, 'SubCategory').reverse()

结果如下;

Greece  : 55
Cyprus  : 55
Austria : 55
France  : 25
Canada  : 25
Hungary : 0
Denmark : 0
Brazil  : 0

我的预期结果如下;

Austria : 55
Cyprus  : 55
Greece  : 55
Canada  : 25
France  : 25
Brazil  : 0
Denmark : 0
Hungary : 0

我试过如下;

_.sortBy(_.sortBy(MyJson, 'SubCategory').reverse(),'Country');

有没有办法将json排序为带有下划线的desc, asc?由于限制了我的开发环境,我没有使用Lodash。

先感谢您。

javascript json underscore.js
2个回答
1
投票

使用下划线表示:你可以排序两次:_(MyJson).chain().sortBy('Country').reverse().sortBy('SubCategory').reverse().value();

This answers正是您要找的。

这里有一个来自下划线文档的东西 - sortBy是一个稳定的算法。这意味着你可以先按你的第二个属性排序,然后按正确的顺序排序,然后按第一个属性排序 - 这将使得两个字段具有相同的排序属性值,其顺序与找到的相同。 (您已经使用第一种排序设置的顺序)

var MyJson = 

[   
    {
        "Country": "Austria",
        "SubCategory": "55",
    }, {
        "Country": "Brazil",
        "SubCategory": "0",
    }, {
        "Country": "Canada",
        "SubCategory": "25",
    }, {
        "Country": "Cyprus",
        "SubCategory": "55",
    },  {
        "Country": "Denmark",
        "SubCategory": "0",
    }, {
        "Country": "France",
        "SubCategory": "25",
    }, {
        "Country": "Greece",
        "SubCategory": "55",
    }, {
        "Country": "Hungary",
        "SubCategory": "0",
    }
];
var sortedArray =  _(MyJson).chain().sortBy('Country').reverse().sortBy('SubCategory').reverse().value();

console.log(sortedArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>

4
投票

简单的Javascript方法。

var data = [{ Country: "Austria", SubCategory: "55" }, { Country: "Brazil", SubCategory: "0" }, { Country: "Canada", SubCategory: "25" }, { Country: "Cyprus", SubCategory: "55" }, { Country: "Denmark", SubCategory: "0" }, { Country: "France", SubCategory: "25" }, { Country: "Greece", SubCategory: "55" }, { Country: "Hungary", SubCategory: "0" }];

data.sort(function (a, b) {
    return b.SubCategory - a.SubCategory || a.Country.localeCompare(b.Country);
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
© www.soinside.com 2019 - 2024. All rights reserved.