我有一个具有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",
}
];发布于 2015-06-09 13:30:13
这在某种程度上与稳定排序有关。确保稳定排序的典型方法是添加辅助数据,在发现项目相同的情况下应根据这些辅助数据进行排序。
我在这里使用了两个map操作,类似于用于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));
https://stackoverflow.com/questions/30707012
复制相似问题