按顺序对数组对象进行排序(最大长度为第一个。)

时间:2018-03-25 16:05:33

标签: javascript arrays sorting object

通过使用此功能,我可以获得升序,如何才能获得逆序最大长度。?

{
    category: [ 
        { name: "Cat1", elements : [ 
            { name: name, id: id } ] 
        },
        { name: "Cat2", elements : [ 
            { name: name, id: id },
            { name: name, id: id },
            { name: name, id: id } ] 
        }, 
        { name: "Cat3", elements : [ 
            { name: name, id: id },
            { name: name, id: id } ] 
        }
    ]
}

我的预期结果是:

{
    category: [ 
        { name: "Cat1", elements : [ 
            { name: name, id: id },
            { name: name, id: id },
            { name: name, id: id } ] 
        },
        { name: "Cat2", elements : [ 
            { name: name, id: id },
            { name: name, id: id } ] 
        }, 
        { name: "Cat3", elements : [ 
            { name: name, id: id } ] 
        }
    ]
}

这是我的排序:

var sorted_categories = original.category.sort(function (one, other) {
   return one.elements.length - other.elements.length;
});

我想从这个问题反向结果:

How to sort an array of objects based on a the length of a nested array in javascript

2 个答案:

答案 0 :(得分:1)

 array = array.reverse();

刚刚反转阵列?

答案 1 :(得分:0)

反转减法的操作数。