How To sort an array of nested objects in javascript

后端 未结 2 715
抹茶落季
抹茶落季 2021-01-16 06:40

I have an array like this

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


        
相关标签:
2条回答
  • 2021-01-16 06:52
    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);
    

    This should re-order the array for any number of nested levels.

    0 讨论(0)
  • 2021-01-16 07:05

    Use Array.prototype.sort and call it on array and subsequently on each element of array with an appropriate compare function. Something like this should work:

    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);
      });
    });
    
    0 讨论(0)
提交回复
热议问题