Javascript排序自定义比较器函数 - 对排序数组进行排序 [英] Javascript sort custom comparator function - sorting a sorted array
问题描述
我有以下形式的对象数组:
I have an array of objects of the following form:
arr[0] = { 'item1' : 1234, 'item2' : 'a string' };
我先按'item1'排序
这很简单。现在我想再次排序 arr
(按'item1'
排序),但这次是'item2'
但仅适用于'item1'
相同的元素。最终的数组如下所示:
I sort it first by 'item1'
which is straightforward. Now i want to sort arr
(which is sorted by 'item1'
) again but this time by 'item2'
but only for the elements where 'item1'
is the same. The final array would look like:
arr = [
{ 'item1' : 1234, 'item2' : 'apple' },
{ 'item1' : 1234, 'item2' : 'banana' },
{ 'item1' : 1234, 'item2' : 'custard' },
{ 'item1' : 2156, 'item2' : 'melon' },
{ 'item1' : 4345, 'item2' : 'asparagus' }
];
我试着为第二种情况写一个排序函数,如下所示:
I tried to write a sorting function for the second case like so:
arr.sort(function(a,b){
if(a.item1 === b.item1){
return a.item2 > b.item2 ? 1 : a.item2 < b.item2 : -1 : 0;
}
});
我可以在一个函数中合并两个排序以获得最终的排序数组但是会出现这种情况我只需按'item1'
或只需'item2'
进行排序。
I could combine the two sorts in one function to get the final sorted array but there will be cases where I'll have to sort by just 'item1'
or just 'item2'
.
推荐答案
你可以有四种不同的比较功能 - 一种按item1排序,一种按item2排序,一种按item1然后按item2排序item2然后item1。
You can have four different comparison functions - one sorting by item1, one by item2, one by item1 then item2 and one by item2 then item1.
例如:
arr.sort(function(a,b){
if(a.item1 == b.item1){
return a.item2 > b.item2 ? 1 : a.item2 < b.item2 ? -1 : 0;
}
return a.item1 > b.item1 ? 1 : -1;
});
这篇关于Javascript排序自定义比较器函数 - 对排序数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!