简体   繁体   English

根据另一个属性的升序对排序的对象数组进行排序

[英]Sort a sorted object array based on ascending order of another attribute

I have an array of objects having attributes TechType and ProductName . 我有一组具有TechTypeProductName属性的对象。 The given array is already sorted by TechType (not necessarily alphabetically); 给定的数组已经按TechType排序(不一定按字母顺序); now within this sorted array, it has to be further sorted by ascending order based on ProductName . 现在在这个有序数组中,它必须按照ProductName升序进一步排序。

var products= [
    {
        "TechType": "ADSL",
        "ProductName": " Zen ADSL Services",
            }, {
        "TechType": "ADSL",
        "ProductName": "ADSL Services",
            }, {
        "TechType": "T1",
        "ProductName": "T1-Voice",
},{
      "TechType": "T1",
        "ProductName": " Aviate T1-Voice",


 }
];

The sorted array should be 排序的数组应该是

  var products= [
        {
            "TechType": "ADSL",
            "ProductName": " ADSL Services",
                }, {
            "TechType": "ADSL",
            "ProductName": "Zen ADSL Services",
                }, {
            "TechType": "T1",
            "ProductName": " Aviate T1-Voice",
    },{
          "TechType": "T1",
            "ProductName": " T1-Voice",


     }
    ];

This is somewhat related to stable sort. 这与稳定排序有些相关。 The typical way to ensure a stable sort is by adding auxiliary data by which should be sorted in case items are found to be the same. 确保稳定排序的典型方法是添加辅助数据,以便在发现项目相同时对其进行排序。

I'm doing this here using two map operations, similar to what you would use for a Schwartzian Transform; 我在这里使用两个map操作,类似于你用于Schwartzian变换的操作; the auxiliary data is used only if the tech types don't match between two items. 仅当技术类型在两个项目之间不匹配时才使用辅助数据。

To demonstrate the correct behaviour I've moved the items around so that tech types are ordered in reverse order from the question. 为了证明正确的行为,我移动了项目,以便技术类型按照问题的相反顺序排序。

 var products = [{ "TechType": "T1", "ProductName": "T1-Voice", },{ "TechType": "T1", "ProductName": "Aviate T1-Voice", }, { "TechType": "ADSL", "ProductName": "Zen ADSL Services", }, { "TechType": "ADSL", "ProductName": "ADSL Services", }]; function sortByStableProperty(array, prop, fn) { // decorate var temp = array.map(function(item, index) { return [item, index]; }); temp.sort(function(a, b) { // sort by auxiliary data or callback function return a[0][prop] == b[0][prop] ? fn(a[0], b[0]) : a[1] - b[1]; }); // undecorate return temp.map(function(item) { return item[0]; }); } // actual sort products = sortByStableProperty(products, 'TechType', function(a, b) { return a.ProductName.localeCompare(b.ProductName); }); console.log(JSON.stringify(products)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM