How to sort an array of objects by multiple fields?

后端 未结 30 2333
北恋
北恋 2020-11-21 11:34

From this original question, how would I apply a sort on multiple fields?

Using this slightly adapted structure, how would I sort city (ascending) & then price (

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 12:25

    This is a complete cheat but I think that it adds value to this question because it's basically a canned library function that you can use out-of-the box.

    If your code has access to lodash or a lodash compatible library like underscore then you can use the _.sortBy method. The snippet below is copied directly from the lodash documentation.

    The commented results in the examples looks like they return arrays of arrays but that's just showing the order and not the actual results which are an array of objects.

    var users = [
      { 'user': 'fred',   'age': 48 },
      { 'user': 'barney', 'age': 36 },
      { 'user': 'fred',   'age': 40 },
      { 'user': 'barney', 'age': 34 }
    ];
    
    _.sortBy(users, [function(o) { return o.user; }]);
     // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
    
    _.sortBy(users, ['user', 'age']);
    // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
    

提交回复
热议问题