按两个字段对JSON对象进行排序

时间:2015-01-16 12:08:20

标签: javascript json

我有跟随json对象

[
{"PARTNERNAME":"Partner 1","DISTANCE":20,"TYPE":"1"},
{"PARTNERNAME":"Partner 2","DISTANCE":14,"TYPE":"2"},
{"PARTNERNAME":"Partner 3","DISTANCE":60,"TYPE":"2"},
{"PARTNERNAME":"Partner 4","DISTANCE":37,"TYPE":"1"},
{"PARTNERNAME":"Partner 5","DISTANCE":25,"TYPE":"2"},
{"PARTNERNAME":"Partner 6","DISTANCE":90,"TYPE":"1"},
{"PARTNERNAME":"Partner 7","DISTANCE":49,"TYPE":"1"}
]

我想首先按类型排序,然后按距离排序,结果如下:

[
{"PARTNERNAME":"Partner 1","DISTANCE":20,"TYPE":"1"},
{"PARTNERNAME":"Partner 4","DISTANCE":37,"TYPE":"1"},
{"PARTNERNAME":"Partner 7","DISTANCE":49,"TYPE":"1"},
{"PARTNERNAME":"Partner 6","DISTANCE":90,"TYPE":"1"},
{"PARTNERNAME":"Partner 2","DISTANCE":14,"TYPE":"2"},
{"PARTNERNAME":"Partner 5","DISTANCE":25,"TYPE":"2"},
{"PARTNERNAME":"Partner 3","DISTANCE":60,"TYPE":"2"}
]

我有以下代码按一个字段对其进行排序,但我可以通过两个字段对其进行排序。这可能吗?

var sortedData = propertyArray.sort(sortByProperty('DISTANCE'));
function sortByProperty(property) {
            'use strict';
            return function (a, b) {
                var sortStatus = 0;
                if (a[property] < b[property]) {
                    sortStatus = -1;
                } else if (a[property] > b[property]) {
                    sortStatus = 1;
                }

                return sortStatus;
            };
        }

2 个答案:

答案 0 :(得分:1)

试试这个:

arr.sort(function(a, b){
    return a.TYPE === b.TYPE ? a.DISTANCE - b.DISTANCE : a.TYPE - b.TYPE
})

答案 1 :(得分:0)

LoDash中有非常有用的功能:

console.log(_.sortBy(propertyArray, "TYPE", "DISTANCE"));

或自定义解决方案:

function sortBy() { var arr = arguments[0]; var fields = [].slice.call(arguments, 1) return arr.sort(function (a, b) { for (var i = 0; i < fields.length; i++) { if (a[fields[i]] != b[fields[i]]) { return a[fields[i]] > b[fields[i]]; } } return 0; }); }

使用:

console.log(sortBy(a, "TYPE", "DISTANCE"));

http://jsfiddle.net/hpzfLq76/