我有一组对象,它们的属性为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",
}
];
排序后的数组应为
var products= [
{
"TechType": "ADSL",
"ProductName": " ADSL Services",
}, {
"TechType": "ADSL",
"ProductName": "Zen ADSL Services",
}, {
"TechType": "T1",
"ProductName": " Aviate T1-Voice",
},{
"TechType": "T1",
"ProductName": " T1-Voice",
}
];
最佳答案
这在某种程度上与稳定排序有关。确保排序稳定的典型方法是添加辅助数据,以防万一发现相同的项目。
我在这里使用两个映射操作执行此操作,类似于对Schwartzian变换所使用的操作。仅当两项之间的技术类型不匹配时才使用辅助数据。
为了演示正确的行为,我已经将项目四处移动,以便按问题的相反顺序对技术类型进行排序。
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));