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

时间:2015-06-08 10:41:00

标签: javascript arrays sorting

我有一组具有error: pack expansion used as argument for non-pack parameter of alias template x_t<Args...> v2; TechType属性的对象。给定的数组已按ProductName排序(不一定按字母顺序);现在在这个有序数组中,它必须按照TechType的升序进一步排序。

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",


 }
];

1 个答案:

答案 0 :(得分:2)

这与稳定排序有些相关。确保稳定排序的典型方法是添加辅助数据,以便在发现项目相同时对其进行排序。

我在这里使用两个地图操作来执行此操作,类似于您将用于Schwartzian变换的操作;仅当技术类型在两个项目之间不匹配时才使用辅助数据。

为了证明正确的行为,我已经移动了这些项目,以便从问题中按相反的顺序排列技术类型。

&#13;
&#13;
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));
&#13;
&#13;
&#13;

相关问题