Sorting an Array of JavaScript Objects a Specific Order (using existing function)

前端 未结 4 1184

Given an array of objects:

{
    key: \"a\",
    value: 42
},
{
    key: \"d\",
    value: 28
},
{
    key: \"c\",
    value: 92
},
{
    key: \"b\",
    value: 8         


        
4条回答
  •  暖寄归人
    2020-12-04 15:26

    Just use indexOf to convert the key to the correct order:

    var order = ["c", "a", "b", "d"];
    _.sortBy(arr, function(obj){ 
        return _.indexOf(order, obj.key);
    });
    

    Fiddle

    If there are a lot of keys, then it would be advantageous to make a hash-map out of the array, like:

    var order = ["c", "a", "b", "d"];
    var orderMap = {};
    _.each(order, function(i) { orderMap[i] = _.indexOf(order, i); });
    

    This makes the key-sorting lookup constant time rather than O(n). (Fiddle)

提交回复
热议问题