如何在javascript中对嵌套对象数组进行排序

时间:2012-06-20 12:45:34

标签: javascript arrays sorting object nested

我有一个像这样的数组

var array = [{
    order: 3,
    sub - array: [{
        order: 2
    },{
        order: 1
    }]
},{
    order: 2,
    sub - array: [{
        order: 2
    },{
        order: 1
    }]
}];​

现在我想对属性order上的完整集合进行排序,因此两者都是外部的 以及内部数组应该根据属性顺序进行排序。

最终输出应如下所示。

var array = [{
    order: 2,
    sub - array: [{
        order: 1
    },{
        order: 2
    }]
},{
    order: 3,
    sub - array: [{
        order: 1
    },{
        order: 2
    }]
}];​

3 个答案:

答案 0 :(得分:4)

var propertySort = function(a, b){
    return a.order > b.order ? 1 : (a.order < b.order ? -1 : 0);
    }

var reorder = function(arr){
    var l = arr.length;
    while (l--){
        if (arr[l]['sub-array']){
            reorder(arr[l]['sub-array']);
        }
    }
arr.sort(propertySort);
};

reorder(arr);

console.log(arr);

这应该为任意数量的嵌套级别重新排序数组。

答案 1 :(得分:1)

使用Array.prototype.sort并在array上调用它,然后使用适当的比较功能在array的每个元素上调用它。 这样的事情应该有效:

array.sort(function (e1, e2) {
  return (e1.order - e2.order);
});

array.forEach(function(e) {
  e["sub-array"].sort(function (e1, e2) {
    return (e1.order - e2.order);
  });
});

答案 2 :(得分:1)

您可以将Agile.js用于此类事情 实际上你传递的是一个表达而不是回调,它以非常好的方式处理嵌套属性和javascript表达式。

用法: _.orderBy(array, expression/callback, reverse[optional])

示例:

var orders = [
  { product: { price: 91.12, id: 1 } },
  { product: { price: 79.21, id: 2 } },
  { product: { price: 99.90, id: 3 } },
  { product: { price: 19.99, id: 4 } }
];

_.orderBy(orders, 'product.price');
// →  [orders[3], orders[1], orders[0], orders[2]]

_.orderBy(orders, '-product.price');
// → [orders[2], orders[0], orders[1], orders[3]]