对象数组的自定义排序顺序 [英] custom sort order on array of objects
问题描述
我知道我们可以定义json对象数组的自定义排序函数。但是如果订单既不是 desc也不是asc
。例如,假设我的数组看起来像:
I know we can define our custom sort function of array of json objects. But what if the order is neither desc nor asc
. For example lets say my array looks like:
[ {
name: 'u'
},
{
name: 'n'
},
{
name: 'a'
},
{
name: 'n',
}
]
输出应如下所示:
[ {
name: 'n'
},
{
name: 'n'
},
{
name: 'a'
},
{
name: 'u',
}
]
所有名称均以 n $开头c $ c>先排序,然后排序。我尝试了以下自定义排序功能:
Where all the names starting with n
are sorted first and then the rest. I have tried the following custom sort function:
_sortByName(a, b){
if (a.name === 'n'){
return 1;
} else if(b.name === 'n'){
return 1;
} else if(a.name < b.name){
return 1;
} else if(a.name > b.name){
return -1;
}
}
但是对象返回的订单是错误的。这里出了什么问题?
But the order returned for objects is wrong. What is going wrong here?
推荐答案
如果您有任意排序顺序,一个选项是将订单分配给数组并且然后使用 indexOf
:
If you have an arbitrary sort order, one option is to assign the order to an array and then use indexOf
:
var sortOrder = ['n', 'a', 'u'];
var myArray = [{
name: 'u'
},
{
name: 'n'
},
{
name: 'a'
},
{
name: 'n'
}
];
myArray.sort(function(a, b) {
return sortOrder.indexOf(a.name) - sortOrder.indexOf(b.name);
});
console.log(myArray);
如果在任一阵列中有多个值,那么创建一个值可能是值得的 - 首先使用索引映射,然后使用 sortOrder [a.name]
。
If you have many values in either array, it might be worthwhile creating a value-index map first and then using sortOrder[a.name]
.
这篇关于对象数组的自定义排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!