【问题标题】:Sort arr by nested sub-array按嵌套子数组对 arr 进行排序
【发布时间】:2016-05-19 19:51:42
【问题描述】:

这是我的任务:

var arr = [
    {
        "name": "ASD",
        "properties": [
            {
                "name": "TypeId",
                "nominalValue": "AC101"
            },
            {
                "name": "Description",
                "nominalValue": "text here"
            }
        ]
    },
    {
        "name": "EWQ",
        "properties": [
            {
                "name": "TypeId",
                "nominalValue": "AB123"
            },
            {
                "name": "Description",
                "nominalValue": "text here"
            }
        ]
    }
]

我想通过在属性 arr 中给出一个name 对其进行排序,它返回它按nominalValue 排序

像这样:

var sortedArr = sortListByPropertyName(arr, 'TypeId'); //Sorts list by 'AB123', 'AC101'..

我的数据集非常大,因此尽可能优化它很重要。我可以使用_.sortBy 和一些聪明的chains 吗?

【问题讨论】:

    标签: javascript sorting underscore.js


    【解决方案1】:

    你可以试试这个:

    function sortListByPropertyName(arr, propName) {
      return _.sortBy(arr, function(obj) {
        return
        _.find(obj.properties, function(prop) {
          return prop.name == propName
        }).nominalValue;
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多